Complex object and model binder ASP.NET MVC

Firstly, the DefaultModelBinder will not bind to fields so you need to use properties

public class HomeModel
{
  public Foo Foo { get; set; }
}

Secondly, the helpers are generating controls based on HomeModel but you posting back to Foo. Either change the POST method to

[HttpPost]
public ActionResult Save(HomeModel model)

or use the BindAttribute to specify the Prefix (which essentially strips the value of prefix from the posted values – so Foo.Bar.Value becomes Bar.Value for the purposes of binding)

[HttpPost]
public ActionResult Save([Bind(Prefix="Foo")]Foo model)

Note also that you should not name the method parameter with the same name as one of your properties otherwise binding will fail and your model will be null.

Leave a Comment