Model Binding in ASP.NET MVC

Model Binding in ASP.NET MVC

In this article, we will discuss mapping asp.net request data to controller action simple parameter types and to the complex parameter using Model Binding in ASP.NET MVC. Please read our last article before proceeding to this article.  We are going to work with the same example that we worked on in our last article i.e. FormCollection in ASP.NET MVC article.

To save the form data to a database table we used the following code in FormCollection in MVC article. From our last article, it should be clear that the FormCollection class will automatically receive the posted form values in the controller action method.

[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
    Employee employee = new Employee();
    // Retrieve form data using form collection
    employee.Name = formCollection["Name"];
    employee.Gender = formCollection["Gender"];
    employee.City = formCollection["City"];
    employee.Salary = Convert.ToDecimal(formCollection["Salary"]);
    employee.DateOfBirth = Convert.ToDateTime(formCollection["DateOfBirth"]);

    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();

    employeeBusinessLayer.AddEmmployee(employee);
    return RedirectToAction("Index");
}

The above controller “Create” HttpPost action method can be re-written using simple types as shown below.

Notice that the create action method has got parameter names that match with the names of the form controls.

The model binder in MVC maps the values of these controls to the respective parameters.

[HttpPost]
public ActionResult Create(string name, string gender, string city, decimal Salary, DateTime dateOfBirth)
{
    Employee employee = new Employee();
    employee.Name = name;
    employee.Gender = gender;
    employee.City = city;
    employee.Salary = Salary;
    employee.DateOfBirth = dateOfBirth;

    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();

    employeeBusinessLayer.AddEmmployee(employee);
    return RedirectToAction("Index");
}
Run the application. Create one employee and see everything is working as expected.

Please note that the order of the parameters does not matter. What matters is the name of the parameter. If the parameter name is different from the form control name then the form data will not be mapped as expected. 

But do we really have to do these mappings manually? The answer is no. Instead of creating simple parameters we can create one parameter of Employee type which will automatically hold the Posted form values as shown below.

Let’s modify the create HttpPost method to accept a complex parameter of Employee Type as shown below.

[HttpPost]
public ActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
    }
    return View();
}
Please note:

1. Model state is being checked using the IsValid boolean property of the ModelState object. We will discuss ModelState in a later article.

2. Instead of passing the individual properties of “Employee” object as parameters to the “Create” action method, we are now passing the “Employee” object itself.

3. The “Employee” object is then handed over to AddEmployee() method of “EmployeeBusinessLayer” class, which takes the responsibility of saving the “Employee” object to the database table.

4. Upon saving the employee the user is then redirected to the “Index” action method.

5. If there are any “Model” validation errors ModelState IsValid returns false. In this case, we stay on the same create view which gives the opportunity to correct the errors and resubmit the page.

ASP.NET MVC Model Binding

ASP.NET MVC Model Binding allows us to map HTTP request data with a model. It is the process of creating .NET objects using the data sent by the browser in an HTTP request. The ASP.NET Web Forms developers who are new to ASP.Net MVC are mostly confused how the values from View get converted to the Model class when it reaches the Action method of the Controller class, so this conversion is done by the Model Binder.

Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model we specify. ASP.NET MVC uses default binders to complete this behind the scene.

In our next article, we will discuss how to use UpdateModel and TryUpdateModel in ASP.NET MVC application.

SUMMARY

In this article, I try to explain Model Binders in ASP.NET MVC application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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