Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, March 5, 2009

Microsoft MVC Digg Sample

So I recently was writing an MVC sample just to familiarize myself with the Microsoft MVC Framework. One of my favorite samples recently was one done by Scott Guthrie for Silver Light. It was a Digg sample so I wanted to make one that was similar to that one. So with no further adieu.


The source code can be downloaded here.

I will be updating it with more features as I build it out and will probably be doing posts to explain the different parts, so keep checking for new entries.

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.