Skip to content

Default MVC model binder doesn’t like fields

by Wayne Denier on February 22nd, 2011
This issue came up both in trying to complete an MVC 3 exercise and recently again when trying to bind an existing Action with a new View model. The form in the View code was posting to the same Action with a few values specified in GET variables, but the variables were being mysteriously swallowed by the Model Binder and not bound despite the variables being named exactly the same as the members of my Model! This is what I discovered both times…
public class ExampleViewModel
{
	public string ThisPropertyWillBeBound { get; set; }
	public int ThisOneToo { get; set; }

	public string ThisFieldWontThough;
	public int WatchOutForThis;
}
If you are defining a custom type as an argument for an Action, the DefaultModelBinder can only map GET variables posted to the Action to Properties on that custom type. In the above example, if I had a WatchOutForThis=really value in my GET variables, the binder ignores this entirely since WatchOutForThis is a field and not a property.

The difference between creating a field and an auto implemented property is so subtle this can be a really tricky one to catch! Check this if your suddenly find values mysteriously missing between receiving the request and getting to your Action code.

From → C#, Web Development

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS