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
I think it's a right design solution. If field are treated like properties, what are properties for? Only for calculated / late binding effects?
ReplyDeleteI use some DTO as action parameter and want posted values be mapped to it. Such limitation enforce me to use properties in my DTO class instead of field.
ReplyDeletethank you so much for sharing such valuable information with us.
ReplyDeleteWorkday Integration Course India
Workday Online Integration Course Hyderabad