繁体   English   中英

在asp.net mvc中删除记录后如何更新视图

[英]How to update view after deleting record in 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 });

        });

您应该知道的第一件事是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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM