MVC Model Binding Not Working with Fields

MVC Model Binding Not Working with Fields

This will be a very quick/simple post.

Maybe this is very clear to most people when they start out developing with ASP.NET MVC but it was not right away with me…

When you are using 2-way model binding in MVC to bind your model to your view and back again, you MUST use properties with getters/setters, not fields.

//Will NOT bind ok public class BindingModel {
    int ID;
    string FirstName;
    string LastName;
    string Website;
}

//WILL bind ok public class BindingModel {
    int ID { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
    string Website { get; set; }
}

I don’t understand why this is, but I have not really looked into it in too much depth. I just made my variables into properties with auto getter/setters and went on my way for now. Hopefully this will save someone some time the next time they are trying to get MVC model binding to work, and can’t figure out why their variables are not being set on the model.

By | 2012-06-26T21:22:52+00:00 June 26th, 2012|Categories: ASP.NET, MVC|Tags: , |1 Comment

About the Author:

One Comment

  1. brent December 4, 2013 at 9:42 am - Reply

    Thanks for the comment Jorge. That does indeed look to be a similar issue to what I experienced. Thanks for sharing.

Leave A Comment