gpt4 book ai didi

javascript - 在asp.net mvc中删除记录后如何更新 View

转载 作者:行者123 更新时间:2023-11-30 14:14:21 25 4
gpt4 key购买 nike

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

我的 Controller 方法

   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 重定向,如下所示:

Controller 操作

[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;
});

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

Controller Action

[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);
});

关于javascript - 在asp.net mvc中删除记录后如何更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53845500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com