O'Reilly logo

Professional ASP.NET MVC 4 by Scott Hanselman, K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Model Binding

Imagine you implemented the Edit action for an HTTP POST, and you didn't know about any of the ASP.NET MVC features that can make your life easy. Since you are a professional web developer, you realize the Edit view is going to post form values to the server. If you want to retrieve those values to update an album, you might choose to pull the values directly from the request:

[HttpPost]
public ActionResult Edit()
{
   var album = new Album();
   album.Title = Request.Form["Title"];
   album.Price = Decimal.Parse(Request.Form["Price"]);
   // ... and so on ...
}

As you can imagine, code like this becomes quite tedious. I've only shown the code to set two properties; you have four or five more to go. You have to pull each property value out of the Form collection (which contains all the posted form values, by name) and move those values into Album properties. Any property that is not of type string will also require a type conversion.

Fortunately, the Edit view carefully named each form input to match with an Album property. If you remember the HTML you looked at earlier, the input for the Title value had the name Title, and the input for the Price value had the name Price. You could modify the view to use different names (like Foo and Bar), but doing so would only make the action code more difficult to write. You'd have to remember the value for Title is in an input named “Foo” — how absurd!

If the input names match the property names, why can't you write a generic piece of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required