Tuesday, November 24, 2009

ASP.NET MVC Model Binding and Model's fields

A Model Binding in MVC provides a simple way to map posted form values to a .NET Framework type and pass the type to an action method as a parameter.

Everything works fine while a model has public properties like this:

public Person
{
public string Id {get;set;}
public string Name {get;set;}
...
}

But if you try to use public fields instead of properties like this:

public Person
{
public string Id;
public string Name;
...
}

you will be surprised to get the model passed to controller's action with no assigned fields.

It happens because ASP.NET MVC use DefaultModelBinder by default which deals with properties but not with fields when map posted form values.

Of course you can use properties instead of fields wherever you need model bindings. But it is an annoying limitation.

ASP.NET MVC allows us to override both the default model binder, as well as add custom model binders, through the ModelBinders static class:


ModelBinders.Binders.DefaultBinder = new SomeCustomDefaultBinder();
ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());

There are more blog entries about ASP.NET MVC Model Binding
6 Tips for ASP.NET MVC Model Binding
A better Model Binder