首页 > 解决方案 > 删除asp.net mvc中的记录后如何更新视图

问题描述

我有一个视图,其中我将记录保存到数据库在同一页面上显示带有 Viewbag 变量的记录我在每条记录前面都有一个删除按钮来删除记录,我希望在删除记录后视图应该得到更新如何做到这一点

我的控制器方法

   public ActionResult Delete(int id)
    {
        db.Delete<Logs>(id);
        return RedirectToAction("Index", new { id });
    }

我的 html 和查询

<button type="button" id="delete" data-id="@item.LogId" class="delete btn btn-default" style="background-color:transparent"><i class="fas fa-times h3" style="color:red;"></i></button>

        $('.delete').click(function () {
            var selectedid = $(this).data("id");
            $.post("@Url.Action("Delete", "Log")", { id: selectedid });

        });

标签: javascriptc#jqueryasp.net-mvc

解决方案


您应该知道的第一件事是RedirectToAction在 AJAX 调用中不起作用,您应该将 URL 传递给重定向,location.href如下所示:

控制器动作

[HttpPost]
public ActionResult Delete(int id)
{
    db.Delete<Logs>(id);

    // other stuff

    string url = this.Url.Action("Index", "Log", new { id = id });

    return Json(url);
}

jQuery

$.post("@Url.Action("Delete", "Log")", { id: selectedid }, function (result) {
    window.location.href = result;
});

或者更好地创建一个包含要通过 AJAX 更新的所有元素的局部视图,然后将其传递给success部分:

控制器动作

[HttpPost]
public ActionResult Delete(int id)
{
    db.Delete<Logs>(id);

    // other stuff

    return PartialView("PartialViewName");
}

jQuery

$.post("@Url.Action("Delete", "Log")", { id: selectedid }, function (result) {
    $('#targetElement').html(result);
});

推荐阅读