I can’t seem to understand child collections in ASP.MVC 4 and Code First binding. I always get an error that the model object is null when it comes to child collections. I can’t even add a check for if the child collection is null because the model is null.
I have verified that in the controller if I create a Batch object and add steps to it, then it will work.
I’m sure this is something simple, but I can’t figure it out.
Here are my objects:
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; }
}
Here is my controller action:
[Authorize]
public ActionResult Create()
{
return View();
}
Here is my 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>
}
Instantiate your model and pass it to the view.
That will solve the NullReference exception on the null model in the view.
However, when you reach the Psot action, Steps (the collection within Batch) will likely be null. To solve this, new up the collection in the constructor like so: