bradygaster.com

fewer resources, less time, more features

ASP.NET MVC Model Binding Example

October 18 2008
Posted to: ,

Scott does an excellent job in his introduction blog post to the new features in the ASP.NET MVC beta release. The Model Binder support is an excellent feature for which I wanted to put forth a simple example. 

In essence, Model Binding allows you to pass an object into your controller methods rather than be required to pass the values of each property for your model that you intend to set within your Controller method. In retrospect, that description sounds pretty harsh and confusing, doesn't it? For now I'll spare you an introduction to Model Binding, Scott's already done an excellent job of that via these two posts

For this example I'll continue with Scott's Person class example. I'll have my Controller method, which takes instances of Person classes. The code below contains all of the Controller and Person Model code for this form-posting scenario. Pay special attention to the Save method, as it demonstrates usage of Model Binding; an instance of the Person class is passed into this method via a parameter named person

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace LearningMvcBeta
{
    namespace LearningMvcBeta.Controllers
    {
        public class PeopleController : Controller
        {
            public ActionResult Create()
            {
                return View();
            }
            public ActionResult Save(Person person)
            {
                return View(person);
            }
        }
    }
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
    }
    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    }
}

 

Then (this is the part I think most examples won't be as clear on as I'm trying to be herein) I'll create my Create view HTML code. This will present the user with a form. Take note, the Person class parameter from the Save method above is named person, so the names of the HTML text elements have to be in the person.PropertyName format. If I'd named the Person parameter p, I'd want to name the HTML text elements using the p.PropertyName format. 

 

<form action="/People/Save" method="post">
    
        <b>Your Name</b>
    
        <label for="FirstName">
            <span>First Name</span>
            <%=Html.TextBox("person.FirstName") %>
        </label>
        
        <label for="LastName">
            <span>Last Name</span>
            <%=Html.TextBox("person.LastName")%>
        </label>
        
        <b>Your Address</b>
        
        <label for="Street">
            <span>Street</span>
            <%=Html.TextBox("person.Address.Street")%>
        </label>
        
        <label for="City">
            <span>City</span>
            <%=Html.TextBox("person.Address.City")%>
        </label>
        
        <label for="State">
            <span>State</span>
            <%=Html.TextBox("person.Address.State")%>
        </label>
        
        <input id="submit" type="submit" value="submit" />
    
    </form>

 

The image below is a screenshot I took of my debugger while testing this code with sample data. This is really powerful stuff - the child Address object defined by the instance of this Person class is sent in as well as was the First and Last name properties, because the Model Binding support trickles down the object graph!

 

Using the nomenclature MVC expects in your HTML form elements results in Model Binding automatically figuring out how to map the HTML form values to the parameter's properties just before the resulting object is fed into the controller method. 

This is one of my favorite new features of ASP.NET MVC, for sure. Thanks a lot, ASP.NET MVC overlords!

Update: Sorry if you've tried to find this post and received an Index out of range error. The syntax highlighter I've been using seems to have pooped the bed. So, I had to make a few changes to the supporting code and I think all's well now. 

Comments Email Permalink Bookmark and Share kick it

Comments

2/11/2009 1:58:10 AM #

KZ

Hi, could you fix the image link. We cannot see your controller code. Thanks.

KZ

2/14/2009 9:16:25 AM #

Auctions UK

Very entertaining Site. I'd have to say nice article if i do say so myself. nice site.  I'm excited and look forward to your Updates.

Auctions UK

3/16/2009 3:08:25 PM #

Slim Fit Blog

Just wanna say thank you for the information that you have been posted on this site. Hope that you will continue doing the same great job! Thanks again webmaster for this useful information.

Slim Fit Blog

4/11/2009 8:10:58 AM #

tnomeralc web design toys

This is really great example.. Very great explanation..

tnomeralc web design toys

4/17/2009 4:47:29 AM #

Model Franchises

Heya - Just looking through some blogengine.net blogs, seems to be a fairly nice platform, certainly better than blogger but still playing with the idea of wordpress.  Any major plus points you have found over WP at all?

Thanks

Matthew

Model Franchises

4/26/2009 4:26:50 AM #

Fred

Hi,
nice example. What's about One-To-Many-Relations? For instance, let's say, a Person can have several adresses...

Regards,
Fred

Fred

4/26/2009 9:40:11 AM #

Fred

Seems like you just have to respect some naming conventions. I've tried the following with success:

Address 1: <%=Html.TextBox("adresses[0].Street")%> <br />
Address 2: <%=Html.TextBox("adresses[1].Street")%> <br />

Person.Addresses was a List<Address>.

Cool Stuff!

Regards,
Manfred

Fred

5/5/2009 6:03:36 AM #

evden eve nakliyat

good article.

evden eve nakliyat

5/29/2009 2:12:06 AM #

Antonio

Hi,

Could you expand this example to include using validators from the Validation Block?

Antonio

6/20/2009 12:29:49 PM #

Gambling casino news

Regarding the question of "Doesn’t having the Model referenced in the View eliminate the need for the Controller?" I always point out that this doesn't mean the Controller is not needed because it's the controller that's responsible for handling the user input and handing the model to the view in the first place.

Gambling casino news

8/3/2009 11:15:39 AM #

Dloadmp3

Nice work guys!
this is just Amazing!
Thanks

Dloadmp3

8/3/2009 4:18:02 PM #

Dloadmp3

cool guys! your posts are great!

Dloadmp3

8/11/2009 7:14:43 PM #

Puneet

Hi,

Thanks for the article.
Can you give an example with Address as collection i.e. a person has list of addresses.

Thanks!

Puneet

8/24/2009 7:51:44 PM #

meilleurs casinos de mises en ligne

Using the nomenclature MVC expects in your HTML form elements results in Model Binding automatically figuring out how to map the HTML form values to the parameter's properties just before the resulting object is fed into the controller method.

meilleurs casinos de mises en ligne