I have a ViewModel which contains a child ViewModel. In a strongly typed Viewed of the parent, I want to RenderPartial on the child, and have results persist following POST.
But the child fields are always null.
This should work, shouldn’t it? I am fairly new to MVC, hopefully I’m missing something simple. Hopefully someone can point it out!
Thanks!
Example
ViewModels
public class EggBoxViewModel
{
public string Brand { get; set; }
public int Price { get; set; }
public EggViewModel Egg { get; set; }
}
public class EggViewModel
{
public string Size { get; set; }
public bool IsBroken { get; set; }
}
Controller
public ActionResult Demo()
{
EggBoxViewModel eggBox = new EggBoxViewModel();
eggBox.Brand = "HappyEggs";
eggBox.Price = 3;
EggViewModel egg = new EggViewModel();
egg.Size = "Large";
egg.IsBroken = false;
eggBox.Egg = egg;
return View(eggBox);
}
[HttpPost]
public ActionResult Demo(EggBoxViewModel eggBox)
{
// here, eggBox.Egg is null
}
Views
“Demo”
@model MvcApplication1.ViewModels.EggBoxViewModel
@using (Html.BeginForm())
{
<h2>EggBox:</h2>
<p>
@Html.LabelFor(model => model.Brand)
@Html.EditorFor(model => model.Brand)
</p>
<p>
@Html.LabelFor(model => model.Price)
@Html.EditorFor(model => model.Price)
</p>
<p>
@{Html.RenderPartial("_Egg", Model.Egg);}
</p>
<input type="submit" value="Submit" />
}
“_Egg” (Partial)
@model MvcApplication1.ViewModels.EggViewModel
<h2>Egg</h2>
<p>
@Html.LabelFor(model => model.Size)
@Html.EditorFor(model => model.Size)
</p>
<p>
@Html.LabelFor(model => model.IsBroken)
@Html.CheckBoxFor(model => model.IsBroken)
</p>
Use an Editor Template, in most cases they’re better for rendering child objects or collections. In your Views\Shared folder create a new folder called EditorTemplates if you don’t already have one. Add a new partial view called EggViewModel and use the same code as in your partial view. This is the bit of magic that renders and names all your fields correctly. It will also handle a collection of EggViewModels without a for each loop as the Editor template will automatically render all the items passed in a collection:
Then in your Demo View use your new Editor Template instead of the partial:
Here are the fields that are rendered:
In the post back you can that the EggViewModel is now part of the EggBoxViewModel:
Also in the ModelState you can see that the Egg fields are prefixed with the property name used in the EggBoxViewModel which makes them a subset of EggBox.
And…the great thing is that if you want to have a collection of Eggs in your EggBox it’s really easy…just make your Egg property on EggBoxViewModel a collection:
Add a second egg:
Change your View to render x.Eggs instead of x.Egg:
Then on post back you’ll see there are 2 Eggs posted back:
The field names have automatically been indexed and named to create a collection of Eggs: