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:

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 ...

Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.