我似乎无法理解 ASP.MVC 4 和 Code First 绑定中的子集合。当涉及到子集合时,我总是收到模型对象为空的错误。我什至无法检查子集合是否为空,因为模型为空。
我已经验证,如果我在控制器中创建一个 Batch 对象并向其添加步骤,那么它将起作用。
我确定这很简单,但我无法弄清楚。
这是我的对象:
public class Batch
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Details { get; set; }
public virtual ICollection<Step> Steps { get; set; }
}
public class Step
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual int Days { get; set; }
public virtual Batch Batch { get; set; }
}
这是我的控制器操作:
[Authorize]
public ActionResult Create()
{
return View();
}
这是我的看法:
@model BC.Models.Batch
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Batch</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Details)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Details)
@Html.ValidationMessageFor(model => model.Details)
</div>
<div>
<h3>Steps</h3>
// Here is where I get a error that model is null
@if(model.Steps != null)
{
foreach(var item in model.Steps)
{
@Html.EditorFor(model => item)
}
}
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}