Friday, 30 September 2011

MVC model binding not setting values

As part of our push towards using the latest and greatest technologies, we have a couple of small web solutions using MVC rather than Webforms. A problem came up recently for one of our devs when trying to model bind a post from a form. The model being passed in to the action method on the controller was chock full of default values for the data types in question, rather than taking the values that the form was providing. Quite a bit of time was spent by him staring at the code trying to figure out why it didn’t work. This was followed by quite a big of time with me staring at his code. Googling for the issue didn’t seem to show up anything obvious either.

Wondering if he’d managed to break the routing setup or something else low-level and fundamental to MVC working correctly, I took a look at the log on code in the template MVC project and saw that it worked just fine. After more staring I finally realised what the problem was. The following code shows essentially the same very very basic model class, firstly with code that doesn’t model bind, secondly with code that does:

public class BadModel
{
    public int MyValue;
}
public class GoodModel
{
    public int MyValue { get; set; }
}

Pretty subtle huh? Trust me when I say that it is far subtler when you don’t have the good and bad code stacked together to see the blatant line length disparity that makes the property stand out. Granted, best practices say that we should always hide member variables behind property getters and setters so you’d hope not to have such a situation arise. However, in day to day usage with VB or C# property and field access does tend to feel identical. Yeah there are multiple methods made when compiled to IL, but Visual Studio hides these from us so it’s not hard for a dev to leave direct access to fields available. So remember, public fields are bad, mkay.

No comments:

Post a Comment