在asp.net mvc中一次更新多个记录
我正在尝试使用asp.net mvc 4
和EF6
创建一个网站,我希望一次更新多行。 但由于某种原因,它不起作用,我得到这样的错误,
System.NullReferenceException:未将对象引用设置为对象的实例
这是我的代码,
调节器
[HttpPost] public ActionResult MakeDue(List BillLists) { if (Session["username"] != null) { if (ModelState.IsValid) { foreach (var BillId in BillLists) { var getDue = db.BillChecks.Where(p => p.id == BillId.id).FirstOrDefault(); getDue.due = BillId.due; } db.SaveChanges(); return RedirectToAction("Success"); } else { return RedirectToAction("Failed"); } } else { return RedirectToAction("Login"); } }
视图
@using (Html.BeginForm("MakeDue", "Home")) { @Html.ValidationSummary(true) @foreach(var item in Model.DueList) { @Html.HiddenFor(modelItem => item.id) @Html.DisplayFor(modelItem => item.flat) @Html.DisplayFor(modelItem => item.name) @Html.TextBoxFor(modelItem => item.due) } }
我的代码中有什么问题吗? 如何立即更新给定的所有输入?
你的第一个问题是你使用foreach
循环生成重复的name
属性,这些属性不会绑定到集合,因此BillLists
参数将始终是一个空集合(它还生成重复的id
属性,这是无效的html)。 您需要使用for
循环或自定义EditorTemplate
for typeof BillCheck
。 使用for
循环,您的视图需要
using (Html.BeginForm("MakeDue", "Home")) { @Html.ValidationSummary(true) @for(int i = 0; i < Model.DueList.Count; i++) { @Html.HiddenFor(m => m.DueList[i].id) @Html.DisplayFor(m => m.DueList[i].flat) @Html.DisplayFor(m => m.DueList[i].name) @Html.TextBoxFor(m => m.DueList[i].due) } }
另请注意, @Html.HiddenFor()
帮助程序需要位于
元素内才能成为有效的html。
下一个问题是视图中的模型不是List
,但它确实包含名为DueList
的属性,它是List
所以你的POST方法需要是
public ActionResult MakeDue(YourModel model)
其中YourModel
是用于生成视图的类名(即在@model ???
语句中)。 然后你需要在控制器方法中循环
foreach (var BillId in model.DueList) { var getDue = db.BillChecks.Where(p => p.id == BillId.id).FirstOrDefault(); if (getDue != null) // add this { getDue.due = BillId.due; } } db.SaveChanges();
另请注意添加if (getDue != null)
检查
旁注:您正在检查if (ModelState.IsValid)
。 建议您返回视图, ModelState
无效,以便用户可以更正任何错误。