Different Ways Of Model Binding In ASP.NET MVC

Introduction

This article will explain model binding in ASP.NET MVC. We will discuss mapping ASP.NET request data to controller action simple parameter types to complex parameters using Model Binding in ASP.NET MVC.

There are different ways of model binding in ASP.NET MVC.

  • Form collection
  • Parameter model binding
  • Entity model binding

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 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 is automatically transferred into a data model we specify. ASP.NET MVC uses default binders to complete this behind the scene.

Step 1

Open Visual Studio 2015 or a version of your choice and create a new project.

Step 2

Choose "web application" project and give an appropriate name for your project. 
 
Different Way Of Model Binding In ASP.NET MVC 

Step 3

Select "empty" template, check on MVC checkbox below, and click OK.
 
Different Way Of Model Binding In ASP.NET MVC 

Step 4

Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
 
Different Way Of Model Binding In ASP.NET MVC 

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".

Different Way Of Model Binding In ASP.NET MVC 

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

Different Way Of Model Binding In ASP.NET MVC 

After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".

Different Way Of Model Binding In ASP.NET MVC 

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".

Different Way Of Model Binding In ASP.NET MVC 

After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".

Different Way Of Model Binding In ASP.NET MVC 

Entity Framework gets added and the respective class gets generated under the Models folder.

Different Way Of Model Binding In ASP.NET MVC 

Step 5

Right-click on Controllers folder and add a controller.

Employee class

  1. namespace MvcModelBinding_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.ComponentModel.DataAnnotations;  
  6.       
  7.     public partial class Employee  
  8.     {  
  9.         public int Id { getset; }  
  10.    
  11.         [Required(ErrorMessage ="Please enter name")]  
  12.         public string Name { getset; }  
  13.    
  14.         [Required(ErrorMessage = "Choose your gender")]  
  15.         public string Gender { getset; }  
  16.    
  17.         [Required(ErrorMessage = "Please enter phone number")]  
  18.         [Display(Name ="Phone Number")]  
  19.         [Phone]  
  20.         public string PhoneNumber { getset; }  
  21.    
  22.         [Required(ErrorMessage = "Please enter email address")]  
  23.         [Display(Name ="Email Address")]  
  24.         [EmailAddress]  
  25.         public string EmailAddress { getset; }  
  26.    
  27.         [Required(ErrorMessage = "Please enter position")]  
  28.         public string Position { getset; }  
  29.    
  30.         [Required(ErrorMessage = "Please enter hire date")]  
  31.         [Display(Name ="Hire Date")]  
  32.         public Nullable<System.DateTime> HireDate { getset; }  
  33.    
  34.         [Required(ErrorMessage = "Please enter salary")]  
  35.         public Nullable<int> Salary { getset; }  
  36.    
  37.         [Required(ErrorMessage = "Please enter Website URL")]  
  38.         [Display(Name ="Website URL")]  
  39.         public string EmployeeWebSite { getset; }  
  40.     }  
  41. }  

Different Way Of Model Binding In ASP.NET MVC

A window will appear. Choose MVC5 Controller-Empty and click "Add".
 
Different Way Of Model Binding In ASP.NET MVC

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home;

Different Way Of Model Binding In ASP.NET MVC

The complete code for Home Controller

Form Collection Model Binding

  1. using MvcModelBinding_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.    
  8. namespace MvcModelBinding_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             return View(employee);  
  18.         }  
  19.    
  20.         public ActionResult Create()  
  21.         {  
  22.             return View();  
  23.         }  
  24.    
  25.         [HttpPost]  
  26.         [ValidateAntiForgeryToken]  
  27.         public ActionResult Create(FormCollection formCollection)  
  28.         {  
  29.             if (ModelState.IsValid)  
  30.             {  
  31.                 Employee employee = new Employee();  
  32.                 employee.Name = formCollection["Name"];  
  33.                 employee.Gender = formCollection["Gender"];  
  34.                 employee.PhoneNumber =formCollection["PhoneNumber"];  
  35.                 employee.EmailAddress = formCollection["EmailAddress"];  
  36.                 employee.Position = formCollection["Position"];  
  37.                 employee.HireDate = Convert.ToDateTime(formCollection["HireDate"]);  
  38.                 employee.Salary = Convert.ToInt32(formCollection["Salary"]);  
  39.                 employee.EmployeeWebSite = formCollection["EmployeeWebSite"];  
  40.                 _dbContext.Employees.Add(employee);  
  41.                 _dbContext.SaveChanges();  
  42.                 RedirectToAction("Index");  
  43.           }  
  44.    
  45.             return View();  
  46.         }  
  47.     }  
  48. }  

Parameter Model Binding

  1. using MvcModelBinding_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.    
  8. namespace MvcModelBinding_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             return View(employee);  
  18.         }  
  19.    
  20.         public ActionResult Create()  
  21.         {  
  22.             return View();  
  23.         }  
  24.    
  25.         [HttpPost]  
  26.         [ValidateAntiForgeryToken]  
  27.         public ActionResult Create(string name,string gender,string phoneNumber, string email, string position, DateTime hireDate,  
  28.             int salary, string employeeWebsite)  
  29.         {  
  30.             if (ModelState.IsValid)  
  31.             {  
  32.                 Employee employee = new Employee();  
  33.                 employee.Name = name;  
  34.                 employee.Gender = gender;  
  35.                 employee.PhoneNumber = phoneNumber;  
  36.                 employee.EmailAddress = email;  
  37.                 employee.Position = position;  
  38.                 employee.HireDate = hireDate;  
  39.                 employee.Salary = salary;  
  40.                 employee.EmployeeWebSite = employeeWebsite;  
  41.                 _dbContext.Employees.Add(employee);  
  42.                 _dbContext.SaveChanges();  
  43.                 RedirectToAction("Index");  
  44.           }  
  45.    
  46.             return View();  
  47.         }  
  48.     }  
  49. }  

Entity Model Binding

  1. using MvcModelBinding_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.    
  8. namespace MvcModelBinding_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             return View(employee);  
  18.         }  
  19.    
  20.         public ActionResult Create()  
  21.         {  
  22.             return View();  
  23.         }  
  24.    
  25.         [HttpPost]  
  26.         [ValidateAntiForgeryToken]  
  27.         public ActionResult Create(Employee employee)  
  28.         {  
  29.             if (ModelState.IsValid)  
  30.             {  
  31.                 _dbContext.Employees.Add(employee);  
  32.                 _dbContext.SaveChanges();  
  33.                 RedirectToAction("Index");  
  34.           }  
  35.    
  36.             return View();  
  37.         }  
  38.     }  
  39. }  

Step 6

Right-click on Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page), and click on "Add.
 
Different Way Of Model Binding In ASP.NET MVC 

Code for Index View

  1. @model IEnumerable<MvcModelBinding_Demo.Models.Employee>  
  2.    
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.    
  7. <h2>Index</h2>  
  8.    
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11. </p>  
  12. <table class="table">  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Name)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Gender)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.PhoneNumber)  
  22.         </th>  
  23.         <th>  
  24.             @Html.DisplayNameFor(model => model.EmailAddress)  
  25.         </th>  
  26.         <th>  
  27.             @Html.DisplayNameFor(model => model.Position)  
  28.         </th>  
  29.         <th>  
  30.             @Html.DisplayNameFor(model => model.HireDate)  
  31.         </th>  
  32.         <th>  
  33.             @Html.DisplayNameFor(model => model.Salary)  
  34.         </th>  
  35.         <th>  
  36.             @Html.DisplayNameFor(model => model.EmployeeWebSite)  
  37.         </th>  
  38.         <th></th>  
  39.     </tr>  
  40.    
  41. @foreach (var item in Model) {  
  42.     <tr>  
  43.         <td>  
  44.             @Html.DisplayFor(modelItem => item.Name)  
  45.         </td>  
  46.         <td>  
  47.             @Html.DisplayFor(modelItem => item.Gender)  
  48.         </td>  
  49.         <td>  
  50.             @Html.DisplayFor(modelItem => item.PhoneNumber)  
  51.         </td>  
  52.         <td>  
  53.             @Html.DisplayFor(modelItem => item.EmailAddress)  
  54.         </td>  
  55.         <td>  
  56.             @Html.DisplayFor(modelItem => item.Position)  
  57.         </td>  
  58.         <td>  
  59.             @Html.DisplayFor(modelItem => item.HireDate)  
  60.         </td>  
  61.         <td>  
  62.             @Html.DisplayFor(modelItem => item.Salary)  
  63.         </td>  
  64.         <td>  
  65.             @Html.DisplayFor(modelItem => item.EmployeeWebSite)  
  66.         </td>  
  67.         <td>  
  68.             @Html.ActionLink("Edit""Edit"new { id=item.Id }) |  
  69.             @Html.ActionLink("Details""Details"new { id=item.Id }) |  
  70.             @Html.ActionLink("Delete""Delete"new { id=item.Id })  
  71.         </td>  
  72.     </tr>  
  73. }  
  74.    
  75. </table>  

Code for Create View

  1. @model MvcModelBinding_Demo.Models.Employee  
  2.    
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.    
  7. <h2>Create</h2>  
  8.    
  9.    
  10. @using (Html.BeginForm())   
  11. {  
  12.     @Html.AntiForgeryToken()  
  13.       
  14.     <div class="form-horizontal">  
  15.         <h4>Employee</h4>  
  16.         <hr />  
  17.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  18.         <div class="form-group">  
  19.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  20.             <div class="col-md-10">  
  21.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  22.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  23.             </div>  
  24.         </div>  
  25.    
  26.         <div class="form-group">  
  27.             @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })  
  28.             <div class="col-md-10">  
  29.                 @Html.DropDownList("Gender"new List<SelectListItem>() {  
  30.                new SelectListItem { Text="Male",Value="Male"},  
  31.                new SelectListItem { Text="Female", Value="Female"}  
  32.            },new { @class = "form-control" } )  
  33.    
  34.                 @Html.ValidationMessageFor(model => model.Gender, ""new { @class = "text-danger" })  
  35.             </div>  
  36.         </div>  
  37.    
  38.         <div class="form-group">  
  39.             @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })  
  40.             <div class="col-md-10">  
  41.                 @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })  
  42.                 @Html.ValidationMessageFor(model => model.PhoneNumber, ""new { @class = "text-danger" })  
  43.             </div>  
  44.         </div>  
  45.    
  46.         <div class="form-group">  
  47.             @Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { @class = "control-label col-md-2" })  
  48.             <div class="col-md-10">  
  49.                 @Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })  
  50.                 @Html.ValidationMessageFor(model => model.EmailAddress, ""new { @class = "text-danger" })  
  51.             </div>  
  52.         </div>  
  53.    
  54.         <div class="form-group">  
  55.             @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })  
  56.             <div class="col-md-10">  
  57.                 @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } })  
  58.                 @Html.ValidationMessageFor(model => model.Position, ""new { @class = "text-danger" })  
  59.             </div>  
  60.         </div>  
  61.    
  62.         <div class="form-group">  
  63.             @Html.LabelFor(model => model.HireDate, htmlAttributes: new { @class = "control-label col-md-2" })  
  64.             <div class="col-md-10">  
  65.                 @Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { @class = "form-control" } })  
  66.                 @Html.ValidationMessageFor(model => model.HireDate, ""new { @class = "text-danger" })  
  67.             </div>  
  68.         </div>  
  69.    
  70.         <div class="form-group">  
  71.             @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })  
  72.             <div class="col-md-10">  
  73.                 @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })  
  74.                 @Html.ValidationMessageFor(model => model.Salary, ""new { @class = "text-danger" })  
  75.             </div>  
  76.         </div>  
  77.    
  78.         <div class="form-group">  
  79.             @Html.LabelFor(model => model.EmployeeWebSite, htmlAttributes: new { @class = "control-label col-md-2" })  
  80.             <div class="col-md-10">  
  81.                 @Html.EditorFor(model => model.EmployeeWebSite, new { htmlAttributes = new { @class = "form-control" } })  
  82.                 @Html.ValidationMessageFor(model => model.EmployeeWebSite, ""new { @class = "text-danger" })  
  83.             </div>  
  84.         </div>  
  85.    
  86.         <div class="form-group">  
  87.             <div class="col-md-offset-2 col-md-10">  
  88.                 <input type="submit" value="Create" class="btn btn-default" />  
  89.             </div>  
  90.         </div>  
  91.     </div>  
  92. }  
  93.    
  94. <div>  
  95.     @Html.ActionLink("Back to List""Index")  
  96. </div>  

Step 7

Build and run the project by pressing Ctrl+F5.
 
Different Way Of Model Binding In ASP.NET MVC
 
Different Way Of Model Binding In ASP.NET MVC