ASP.NET MVC model binding with nested child models and PartialViews
Posted
by MartinHN
on Stack Overflow
See other posts from Stack Overflow
or by MartinHN
Published on 2010-03-17T13:24:15Z
Indexed on
2010/03/17
14:11 UTC
Read the original article
Hit count: 753
asp.net-mvc
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!
© Stack Overflow or respective owner