Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex object and model binder ASP.NET MVC

People also ask

What are model binders in ASP.NET MVC?

Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.

Is MVC two-way data binding?

So the two-way data binding means we can perform both read and write operations. In our previous article Data Binding in Spring MVC with Example, we have discussed how to write-to-variable task and in this article, we mainly focus on the read-from-a-variable task.

What is FromBody ASP NET core?

[FromBody] attributeThe ASP.NET Core runtime delegates the responsibility of reading the body to an input formatter. Input formatters are explained later in this article. When [FromBody] is applied to a complex type parameter, any binding source attributes applied to its properties are ignored.


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.


I just discovered another reason this can happen, which is if your property is named Settings! Consider the following View model:

public class SomeVM
{
    public SomeSettings DSettings { get; set; } // named this way it will work

    public SomeSettings Settings { get; set; } // property named 'Settings' won't bind!

    public bool ResetToDefault { get; set; }
}

In code, if you bind to the Settings property, it fails to bind (not just on post but even on generating the form). If you rename Settings to DSettings (etc) it suddenly works again.