Model Binding in ASP.NET MVC

Model Binding in ASP.NET MVC Application

In this article, I am going to discuss Model Binding in ASP.NET MVC Application. Please read our previous article before proceeding to this article where we discussed how to bind Model Data using FormCollection Class in ASP.NET MVC Application.  We are also going to work with the same example that we worked on in our previous article.

Here in this article, we will discuss how to map ASP.NET MVC request data to controller action using simple parameter types as well as using complex parameters using Model Binding.

Model Binding in ASP.NET MVC

Let us first recap of what we did in our previous article.

In our previous article, in order to save the form data to a database table, we use Form Collection class as shown in the below code. 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 “Create” HttpPost action method can be re-written using simple types as shown below. Notice here 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.

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

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. 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();
}
Points to Note:
  1. The 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 the “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 the AddEmployee() method of the “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.
What is Model Binding in ASP.NET MVC?

The 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 about 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 are 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. Here, 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 needs. 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 *