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.
Step 3
Select "empty" template, check on MVC checkbox below, and click OK.
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.
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".
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
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".
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".
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
Entity Framework gets added and the respective class gets generated under the Models folder.
Step 5
Right-click on Controllers folder and add a controller.
Employee class
- namespace MvcModelBinding_Demo.Models
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
-
- public partial class Employee
- {
- public int Id { get; set; }
-
- [Required(ErrorMessage ="Please enter name")]
- public string Name { get; set; }
-
- [Required(ErrorMessage = "Choose your gender")]
- public string Gender { get; set; }
-
- [Required(ErrorMessage = "Please enter phone number")]
- [Display(Name ="Phone Number")]
- [Phone]
- public string PhoneNumber { get; set; }
-
- [Required(ErrorMessage = "Please enter email address")]
- [Display(Name ="Email Address")]
- [EmailAddress]
- public string EmailAddress { get; set; }
-
- [Required(ErrorMessage = "Please enter position")]
- public string Position { get; set; }
-
- [Required(ErrorMessage = "Please enter hire date")]
- [Display(Name ="Hire Date")]
- public Nullable<System.DateTime> HireDate { get; set; }
-
- [Required(ErrorMessage = "Please enter salary")]
- public Nullable<int> Salary { get; set; }
-
- [Required(ErrorMessage = "Please enter Website URL")]
- [Display(Name ="Website URL")]
- public string EmployeeWebSite { get; set; }
- }
- }
A window will appear. Choose MVC5 Controller-Empty and click "Add".
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;
The complete code for Home Controller
Form Collection Model Binding
- using MvcModelBinding_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcModelBinding_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext = new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(FormCollection formCollection)
- {
- if (ModelState.IsValid)
- {
- Employee employee = new Employee();
- employee.Name = formCollection["Name"];
- employee.Gender = formCollection["Gender"];
- employee.PhoneNumber =formCollection["PhoneNumber"];
- employee.EmailAddress = formCollection["EmailAddress"];
- employee.Position = formCollection["Position"];
- employee.HireDate = Convert.ToDateTime(formCollection["HireDate"]);
- employee.Salary = Convert.ToInt32(formCollection["Salary"]);
- employee.EmployeeWebSite = formCollection["EmployeeWebSite"];
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- RedirectToAction("Index");
- }
-
- return View();
- }
- }
- }
Parameter Model Binding
- using MvcModelBinding_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcModelBinding_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext = new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(string name,string gender,string phoneNumber, string email, string position, DateTime hireDate,
- int salary, string employeeWebsite)
- {
- if (ModelState.IsValid)
- {
- Employee employee = new Employee();
- employee.Name = name;
- employee.Gender = gender;
- employee.PhoneNumber = phoneNumber;
- employee.EmailAddress = email;
- employee.Position = position;
- employee.HireDate = hireDate;
- employee.Salary = salary;
- employee.EmployeeWebSite = employeeWebsite;
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- RedirectToAction("Index");
- }
-
- return View();
- }
- }
- }
Entity Model Binding
- using MvcModelBinding_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcModelBinding_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext = new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(Employee employee)
- {
- if (ModelState.IsValid)
- {
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- RedirectToAction("Index");
- }
-
- return View();
- }
- }
- }
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.
Code for Index View
- @model IEnumerable<MvcModelBinding_Demo.Models.Employee>
-
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- <p>
- @Html.ActionLink("Create New", "Create")
- </p>
- <table class="table">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Gender)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.PhoneNumber)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.EmailAddress)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Position)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.HireDate)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Salary)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.EmployeeWebSite)
- </th>
- <th></th>
- </tr>
-
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Gender)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.PhoneNumber)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.EmailAddress)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Position)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.HireDate)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Salary)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.EmployeeWebSite)
- </td>
- <td>
- @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
- @Html.ActionLink("Details", "Details", new { id=item.Id }) |
- @Html.ActionLink("Delete", "Delete", new { id=item.Id })
- </td>
- </tr>
- }
-
- </table>
Code for Create View
- @model MvcModelBinding_Demo.Models.Employee
-
- @{
- ViewBag.Title = "Create";
- }
-
- <h2>Create</h2>
-
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <h4>Employee</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.DropDownList("Gender", new List<SelectListItem>() {
- new SelectListItem { Text="Male",Value="Male"},
- new SelectListItem { Text="Female", Value="Female"}
- },new { @class = "form-control" } )
-
- @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.EmailAddress, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Position, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.HireDate, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.HireDate, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.EmployeeWebSite, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.EmployeeWebSite, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.EmployeeWebSite, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
Step 7
Build and run the project by pressing Ctrl+F5.