在asp.net mvc中一次更新多个记录

Shi*_*han 8 c# asp.net asp.net-mvc

我正在尝试使用asp.net mvc 4&EF6我想要一次更新多行的网站.但由于某种原因,它不起作用,我得到这样的错误,

System.NullReferenceException:未将对象引用设置为对象的实例

这是我的代码,

调节器

[HttpPost]
    public ActionResult MakeDue(List<BillCheck> 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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

视图

@using (Html.BeginForm("MakeDue", "Home"))
{
    @Html.ValidationSummary(true)
    @foreach(var item in Model.DueList)
    {
        @Html.HiddenFor(modelItem => item.id)
        <tr>
            <td>@Html.DisplayFor(modelItem => item.flat)</td>
            <td>@Html.DisplayFor(modelItem => item.name)</td>
            <td>@Html.TextBoxFor(modelItem => item.due)</td>
        </tr>
    }
    <input type="submit" class="btn btn-success" value="Update" />
}
Run Code Online (Sandbox Code Playgroud)

我的代码中有什么问题吗?如何一次更新due给定的所有输入?

小智 24

你的第一个问题是你使用foreach循环生成了name不会绑定到集合的重复属性,因此BillLists参数将始终是一个空集合(它还生成重复的id属性,这是无效的html).您需要为typeof 使用for循环或自定义.使用循环,您的视图需要EditorTemplateBillCheckfor

using (Html.BeginForm("MakeDue", "Home"))
{
  @Html.ValidationSummary(true)
  @for(int i = 0; i < Model.DueList.Count; i++)
  {

    <tr>
      <td>
        @Html.HiddenFor(m => m.DueList[i].id)
        @Html.DisplayFor(m => m.DueList[i].flat)</td>
      <td>@Html.DisplayFor(m => m.DueList[i].name)</td>
      <td>@Html.TextBoxFor(m => m.DueList[i].due)</td>
    </tr>
  }
  <input type="submit" class="btn btn-success" value="Update" />
}
Run Code Online (Sandbox Code Playgroud)

另请注意,@Html.HiddenFor()帮助程序需要位于<td>元素内部才能成为有效的html.

下一个问题是视图中的模型不是typeof List<BillCheck>,但它确实包含一个名为DueListtypeof 的属性,List<BillCheck>因此你的POST方法需要是

public ActionResult MakeDue(YourModel model)
Run Code Online (Sandbox Code Playgroud)

这里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();
Run Code Online (Sandbox Code Playgroud)

另请注意添加if (getDue != null)支票

旁注:你正在检查if (ModelState.IsValid).建议您返回视图ModelState无效,以便用户可以更正任何错误.