Need help using the DefaultModelBinder for a nested model.
Posted
by Will
on Stack Overflow
See other posts from Stack Overflow
or by Will
Published on 2010-04-01T21:03:23Z
Indexed on
2010/04/01
23:23 UTC
Read the original article
Hit count: 591
asp.net-mvc-2
|defaultmodelbinder
There are a few related questions, but I can't find an answer that works.
Assuming I have the following models:
public class EditorViewModel
{
public Account Account {get;set;}
public string SomeSimpleStuff {get;set;}
}
public class Account
{
public string AccountName {get;set;}
public int MorePrimitivesFollow {get;set;}
}
and a view that extends ViewPage<EditorViewModel>
which does the following:
<%= Html.TextBoxFor(model => model.Account.AccountName)%>
<%= Html.ValidationMessageFor(model => model.Account.AccountName)%>
<%= Html.TextBoxFor(model => model.SomeSimpleStuff )%>
<%= Html.ValidationMessageFor(model => model.SomeSimpleStuff )%>
and my controller looks like:
[HttpPost]
public virtual ActionResult Edit(EditorViewModel account)
{ /*...*/ }
How can I get the DefaultModelBinder to properly bind my EditorViewModel? Without doing anything special, I get an empty instance of my EditorViewModel with everything null or default.
The closest I've come is by calling UpdateModel
manually:
[HttpPost]
public virtual ActionResult Edit(EditorViewModel account)
{
account.Account = new Account();
UpdateModel(account.Account, "Account");
// this kills me:
UpdateModel(account);
This successfully updates my Account property model, but when I call UpdateModel on account
(to get the rest of the public properties of my EditorViewModel) I get the completely unhelpful "The model of type ... could not be updated." There is no inner exception, so I can't figure out what's going wrong.
What should I do with this?
© Stack Overflow or respective owner