猿问

删除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 });


        });


郎朗坤
浏览 176回答 1
1回答

慕码人2483693

您应该知道的第一件事是RedirectToAction在 AJAX 调用中不起作用,您应该将 URL 传递给重定向,location.href如下所示:控制器动作[HttpPost]public ActionResult Delete(int id){&nbsp; &nbsp; db.Delete<Logs>(id);&nbsp; &nbsp; // other stuff&nbsp; &nbsp; string url = this.Url.Action("Index", "Log", new { id = id });&nbsp; &nbsp; return Json(url);}jQuery$.post("@Url.Action("Delete", "Log")", { id: selectedid }, function (result) {&nbsp; &nbsp; window.location.href = result;});或者更好地创建一个包含要通过 AJAX 更新的所有元素的局部视图,然后将其传递给success部分:控制器动作[HttpPost]public ActionResult Delete(int id){&nbsp; &nbsp; db.Delete<Logs>(id);&nbsp; &nbsp; // other stuff&nbsp; &nbsp; return PartialView("PartialViewName");}jQuery$.post("@Url.Action("Delete", "Log")", { id: selectedid }, function (result) {&nbsp; &nbsp; $('#targetElement').html(result);});
随时随地看视频慕课网APP
我要回答