我有一个局部视图用于编辑集合(在这里我已将其中大部分截断了):
@using CustomSurveyTool.Models
@model Basiclife
<div class="editorRow">
@using (Html.BeginCollectionItem(""))
{
<div class="form-horizontal">
<div class="row">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="col-md-2">
@Html.LabelFor(model => model.Plantype, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Plantype, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Plantype, "", new { @class = "text-danger" })
</div>
<div class="col-md-1">
<a href="#" class="deleteRow">X</a>
</div>
</div>
</div>
}
</div>
这是包装视图的一部分:
@using CustomSurveyTool.Models
@model IEnumerable<Basiclife>
@{
ViewBag.Title = "CreateBasicLifeResponse";
}
<h2>Basic Life Insurance Plans</h2>
<div id="planList">
@using (Html.BeginForm())
{
<div id="editorRows">
@foreach (var item in Model)
{
@Html.Partial("_BasicLifeResponse", item)
}
</div>
@Html.ActionLink("Add", "BasicLifeResponse", null, new { id = "addItem", @class = "button" });
<input type="submit" value="submit" />
}
</div>
回发给该控制器的人
[HttpPost]
public ActionResult CreateBasicLifeResponse(IEnumerable<Basiclife> model)
{
foreach(var item in model)
{
string currentUserId = User.Identity.GetUserId();
Response targetresponse = db.response.FirstOrDefault(x => x.Userid == currentUserId);
int responseid = targetresponse.Id;
item.ResponseId = responseid;
db.basiclife.Add(item);
db.SaveChanges();
}
List<Basiclife> basiclife = new List<Basiclife>();
return View(model);
}
提交表单后,我在foreach(var item in model)
上收到NullReferenceException。可能是什么原因造成的?
答案 0 :(得分:0)
您需要遵循MVC命名约定,该约定涉及在Razor视图中使用带有索引的for循环,而不是foreach。查看这篇文章: How to pass IEnumerable list to controller in MVC including checkbox state?。 我建议使用本文中介绍的“编辑器模板”方法,它与您当前的PartialView方法最相似。