ASP.NET MVC model binding with nested child models and PartialViews
- by MartinHN
I have a model called Page, which has a property called Content of type EditableContent. EditableContent have SidebarLeft and SidebarRight (type TemplateSection).
I want to edit the Page instance, in my Edit.aspx view. Because EditableContent is also attached to other models, I have a PartialView called ContentEditor.ascx that is strongly typed and takes an instance of EditableContent and renders it.
The rendering part all works fine, but when I post - everything inside my ContentEditor is not binded - which means that Page.Content is null.
On the PartialView, I use the strongly typed Html Helpers to do this:
<%= Html.HiddenFor(m => m.TemplateId) %>
And so on. But because the input elements on the form, rendered by ContentEditor.ascx, does not get the "Content" prefix to its id attribute - the values are not binded to Page.
So to overcome this, I've definitely done the wrong thing. Used loosely typed Html Helpers instead:
<%= Html.Hidden("Content.TemplateId", Model.TemplateId) %>
And when I'm dealing with a property that is a List of something it gets very ugly. I then have to render collection indexes manually... doh
What am I missing here? A BindPrefix in the controller action that the Form is being posted to?
Should I put both Page and EditableContent as parameters to the controller action:
public ActionResult Edit(Page page, EditableContent content) { ... }
Any help is much appreciated!