Monday, March 2, 2009

Microsoft MVC Tip #1

Well here is my first tip for MVC, how nice that I actually hit a head scratcher.

So recently I was doing some Model binding in MVC, and couldn’t get the binding to work. I had a simple object:

public class SimpleObject 
{
public string TestHiddenField;
public SimpleObject
{
TestHiddenField = "2";
}
}

In my Controller I was assigning the instance of my SimpleObject to my Model:


public ActionResult Index() 
{
ViewData.Model = new SimpleObject();
return View();
}

And in my markup I had this:


<%= Html.Hidden("TestHiddenField") %> 

The markup that was produced was this:



 

Now notice the value is blank. The model should have bound the value “2” to this control and that should have been the value. But without knowing it I did something stupid. I have a public field but it seems that the Model Binder expects a property with a getter and a setter. Well at least a getter.


So to fix the problem I had to fix my SimpleObject:


public class SimpleObject 
{
public string TestHiddenField{ get; set; };
public SimpleObject
{
TestHiddenField = "2";
}
}

So in conclusion it seems that under the covers MVC Model Binder looks for properties and not fields on the object. This is interesting since I would think that it would look for both. Though it is a good practice to use properties rather than fields I just didn’t expect it.

No comments: