Mark Gilbert's Blog

Science and technology, served light and fluffy.

Properly Propertied Programming – ASP.NET MVC 2 Model Properties

The other day, I came across an interesting nuance of the ASP.NET MVC 2 framework.  I built a model class like the following:

Public Class ModelThatDoesntWork

    Public FieldA As String
    Public FieldB As String

End Class

What I meant to do was this, however:

Public Class ModelThatWorks

    Public Property FieldA As String
    Public Property FieldB As String

End Class

See the difference?  In the first, I’ve declared public members FieldA and FieldB, but in the second I’ve declared public properties.

As the name implies, the first class didn’t work, which in this case manifested in a couple of ways.  First, when I created a strongly-typed "Create" view based on ModelThatDoesntWork, none of the usual field controls (label, text box, and validation control) showed up in the markup.

That was odd.  Oh well, perhaps I needed to build the project before adding the view.  Maybe the MVC framework just didn’t see the new class members. 

I proceeded to add that markup by hand.  Adding the field controls didn’t turn up any warnings or errors, so I thought I was out of the woods.  When I tested posting data back from the form, however, I got my second surprise.  The model being posted back didn’t contain any of the data from the form.

    <HttpPost()> _
    Function ViewThatDoesntWork(MyModel As ModelThatDoesntWork) As ActionResult
        ' MyModel properties will be Nothing (since these are strings) - the MVC
        ' framework couldn't find the public members of the ModelThatDoesntWork 
        ' class.  It needs public properties
        Return View("ViewThatDoesntWork", MyModel)
    End Function

I’ve always had the hunch that under the hood, the MVC framework relied on reflection when it came to populating models on postback.  This issue seems to confirm that suspicion.  The framework is specifically looking for model properties.

Check out the MVCModels.zip archive on my SkyDrive at http://tinyurl.com/MarkGilbertSource for a sample application that shows these behaviors.

Advertisements

April 30, 2012 - Posted by | ASP.NET MVC

Sorry, the comment form is closed at this time.

%d bloggers like this: