As promised, we are back with model binders. Model binders are one of the core feature(and powerful)  of asp.net MVC framework. Like everybody else, I switched from web forms to .Net MVC. It was very difficult for me to understand how .net framework binds all the values located at view to the exact object which we are expecting to get at our controller side without worrying about which field value should bind to the some property of class.

Well, behind the scenes , it is Microsoft’s MVC engine works. We are just going to explore how this engine works and the various model binders at our disposal.

What is Model Binder ?

A model binder is responsible for mapping a browser request into an object.

lets have the demo of Model Binders.

Listing 1: Create View.cshtml

@using(Html.BeginForm(“Create”, “ModelBind”))

{

<table>

<tr>

<td> <label for =”Name”>Name</label></td>

</tr>

<tr>

<td>@Html.TextBox(“Name”) </td>

</tr>

<tr>

<td>Class :</td>

</tr>

<tr>

<td>@Html.TextBox(“Class”) </td>

</tr>

<tr>

<td>Section :</td>

</tr>

<tr>

<td>@Html.TextBox(“Section”) </td>

</tr>

</table>

<p>

<input type=”submit” value =”create” />

</p>

}

Listing 2:  Create Action

// POST: /Product/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(Student studentToCreate)

{

// Add product to database

return RedirectToAction(“Index”);

}

Listing 3:

public class Student

{

[Required]

public string Name { get; set; }

[Required]

public string Class { get; set; }

 

}

listing 1 will render three textboxes for Name, Class, and Section respectively and a Submit button.

In listing 2,  the Create action method is expecting an object of type Student to be posted by browser into a method as a parameter.

In listing 3, Note that, though we have three fields in our view page, but in our Student model, there are only two properties Name  and Class.

Now, carefully observe the listing 1 code. We are not explicitly defining what to pass to “Create” action method. Neither we are preparing any object of Type Student  at view page.

This all will be taken care by Default Model Binder. 

A default model binder is smart enough to pick up field values and map it into the required object of corresponding action method mentioned into BeginForm() method of view.

Here, default ModelBinder will bind the value of Name and  Class to its respective property to binder and will leave out Section field as it is.

Types of Model Binders:

 The ASP.NET MVC framework ships with three model binders:

  • Default model binder
  • Form collection model binder
  • HTTP posted file base model binder

Default model binder

 The default model binder is smart enough to create a variety of different types of objects

from a browser request including the following:

  • A primitive type such as a string, decimal, or DateTime.
  • A class such as a Product or Customer
  • An array such as a string or Product
  • A collections such as an IEnumerable<T>, ICollection<T>, IList<T>, T[ ],

Collection<T>, and List<T>.

  • A dictionary such as an IDictionary<TKey, TValue> and Dictionary<TKey, TValue>.

 Working with Complex data model and Default Model Binder

Lets, suppose we have relation of Customer and Address, where address is composite type of clas which further contains street, city and zip properties.

So our classes  will look like as below.

Listing 4:

public class Customer

{

public int Id { get; set; }

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 ZIP { get; set; }

}

Lets have a look at our View.

Listing 5:

@{

ViewBag.Title = “Index”;

}

<h2>Index</h2>

@Html.ValidationSummary(“Please correct the error, before moving forward”)

 

@using (Html.BeginForm(“Create”, “ModelBind”))

{

<fieldset>

<legend>Customer Info</legend>

<p>

<label for=”FirstName”>First Name:</label>

@Html.TextBox(“FirstName”)

@Html.ValidationMessage(“FirstName”, “*”)

</p>

<p>

<label for=”LastName”>Last Name:</label>

@Html.TextBox(“LastName”)

@Html.ValidationMessage(“LastName”, “*”)

</p>

</fieldset>

 

<fieldset>

<legend>Customer Address</legend>

<p>

<label for=”Address.Street”>Street:</label>

@Html.TextBox(“Address.Street”)

@Html.ValidationMessage(“Address.Street”, “*”)

</p>

<p>

<label for=”Address.City”>City:</label>

@Html.TextBox(“Address.City”)

@Html.ValidationMessage(“Address.City”, “*”)

</p>

<p>

<label for=”Address.ZIP”>ZIP:</label>

@Html.TextBox(“Address.ZIP”)

@Html.ValidationMessage(“Address.ZIP”, “*”)

</p>

</fieldset>

<p>

<input type=”submit” value=”Create” />

</p>

 

}

In Listing 5 ,  observe how Address properties are defined in view <label for=”Address.Street”>

Once you hit the submit button , the default model binder will capture all the values and prepare customer object with address fields as well and it will send it to controller to work with.

That’s it guys for now!!! In next post we will discuss about remaining model binders and Bind attribute.

 

Thanks…!

 

Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *