An Overview Of Model Binding In ASP.NET MVC

ASP.NET MVC provides model binding to get from field values in a view. In several cases, model binding to complex types fulfills the same purpose. If the model type to get from the values is known at the time of development, you can mention a parameter of that type. But this is not the case always. And then you need some programmatic model binding. Programmatic model binding permits you to do model binding at runtime which is based on some condition or logic.

An Overview Of Model Binding In ASP DOT NET MVC

Suppose there is a page that captures details about workers doing a job. The EmployeeID, FirstName, and LastName fields are quite straightforward. The tricky thing is to depend on the selection in the Worker Type dropdown list you need to add the values to two different types. When the Worker Type is Employee you wish to bind the values to Employee object and when the Worker Type is Contract then you want to bind values with the ContractWorker object.

Here, the target type is dependent on the selection in the dropdown list. Let’s see how model binding can be used in such situations.

Firstly you need to create a new ASP.NET MVC project and add two model classes: Employee and ContractWorker. These classes are shown below:

public class Employee

{

public int EmployeeID { get, set; }

public string First Name { get, set; }

public string LastName { get, set; }

}

public class contract worker

{

public int EmployeeID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

}

In the above example, both classes area are almost identical but that’s not necessary.

Index view

Next add a new controller (HomeController) and Index view.

<h1>Enter Worker Details</h1>

<form action=”/home/process” method=”post”>

<table cellpadding=”10″ border=”1″>

<tr>

<td>Employee ID :</td>

<td><input type=”text” name=”employeeid” /></td>

</tr>

<tr>

<td>First Name :</td>

<td><input type=”text” name=”firstname” /></td>

</tr>

<tr>

<td>Last Name :</td>

<td><input type=”text” name=”lastname” /></td>

</tr>

<tr>

<td>Worker Type :</td>

<td>

<select name=”workerType”>

<option value=”E”>Employee</option>

<option value=”C”>Contract Worker</option>

</select>

</td>

</tr>

<tr>

<td colspan=”2″>

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

</td>

</tr>

</table>

</form>

The Index view has a <form> which submits to Process action as indicated in the action attribute. Although the above markup uses plain HTML tags, you could use HTML helpers.

UpdateModel() method

Now add the Process () action inside the HomeController as shown below:

[HttpPost]

public ActionResult Process(string workerType)

{

if(workerType==”E”)

{

Employee emp = new Employee();

this.UpdateModel(emp);

//do something with emp

}

if (workerType == “C”)

{

ContractWorker worker = new ContractWorker();

this.UpdateModel(worker);

//do something with worker

}

return View(“Index”);

}

The Process()takes a string parameter – workerType. To mention, workerType is a name of the drop-down list on the Index view. This way you can select the Worker Type in the action. Next two if blocks check the value of worker type. If it is E, a new object of Employee is created. This object would be initially empty. To fill various properties of emp object you need to perform the model binding. To get it done, this task UpdateModel() method of the Controller base class is called. The UpdateModel() method accepts the object and tries to model bind it with from the Request.QueryString or Request.Form collections.

Likewise, the other if blocked, fills the ContractWorker object.

Once done, you can use “emp” and worker objects as per the need of your application.

TryUpdateModel() method

Though the application works as expected there is an issue. Execute the application and enter a string in EmployeeID textbox. The call to UpdateModel() will cause an exception:

The codes give an exception since UpdateModel() cannot convert a string to an integer. You can deal this kind of exception with an alternative – TryUpdateModel() method.

The TryUpdateModel() method is very similar to UpdateModel() but it returns true or false rather throwing an exception. That says that the TryUpdateModel() will return true if everything is fine, otherwise, it would return false. So, the job would be to simply check this return value.The following code shows how to do it.

[HttpPost]

Public ActionResult Process(string worker type)

{

bool flag = false;

if(workerType==”E”)

{

Employee emp = new Employee();

flag = this.TryUpdateModel(emp);

if (flag)

{

//do something with emp

}

}

if (workerType == “C”)

{

ContractWorker worker = new ContractWorker();

flag = this.TryUpdateModel(worker);

if (flag)

{

//do something with worker

}

}

return View(“Index”);

}

}

As mentioned, the return value of TryUpdateModel() is kept in flag variable. If the flag is true then only the application specific processing is executed.

If you wish to run the application again and enter some string value in EmplyeeID textbox, then you won’t get any exception.

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through .NET training program; our institute would be of great help and support. We give a well-structured program for the best Dot Net Course. Among various good institutes of dot net training and placement in PuneCRB Tech has developed its own identity.

Happy Coding!

Codes: Google database

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>