MVC 可变长度集合模型为空



我有一个用于编辑集合的部分视图(其中大部分我在这里截断(:

@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。可能是什么原因造成的?

您需要遵循 MVC 命名约定,该约定涉及在 Razor 视图中使用带有索引的 for 循环而不是 foreach。看看这篇文章: 如何将IE无数列表传递给MVC中的控制器,包括复选框状态? 我推荐文章中描述的编辑器模板方法,它与您当前的 Partial View 方法最相似。

最新更新