javascript - 删除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);
});
推荐阅读
- postgresql - 两组的 PostGIS 最小距离,包括两个表中的其他变量
- c - 在 C 编程中,需要的 L 值是语义错误还是语法错误?
- java - “java.lang.LinkageError:以前为具有名称的不同类型启动加载”的原因
- reactjs - take(eventChannel) 采取所有行动而不是发出的结果
- spring-boot - 春季云任务多个数据源的问题
- c++ - 用于存储通用 lambda 的通用 std::function
- python - Keras 模型编译错误:TypeError:“张量”类型的对象没有 len() model.compile
- python - 从ui文件加载的PySide2 QMainWindow未触发窗口事件
- python - 蛮力 360 度模板匹配 OpenCV Python
- selenium - 如何在 ZAP selenium 中使用 ZAP JxBrowser?