Introduction
This article will explain the Bind attribute in ASP.NET MVC. We will discuss the include and exclude properties from model binding using the Bind Attribute in ASP.NET MVC application.
Step 1
Open SQL Server 2014 or a version of your choice and create a table with some data.
Step 2
Choose the "web application" project and give an appropriate name for your project.
Step 3
Select "empty" template, check on MVC checkbox, 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.
Employee Class
- namespace MvcBindAttribute_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 = "Please choose 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")]
- [DataType(DataType.Currency)]
- public Nullable<int> Salary { get; set; }
-
- [Required(ErrorMessage = "Please enter website")]
- [Display(Name ="Personal Website")]
- [Url]
- public string EmployeeWebSite { get; set; }
- }
- }
Step 5
Right-click the Controllers folder and add a controller.
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 is given below.
- using MvcBindAttribute_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcBindAttribute_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext = new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- [HttpGet]
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create([Bind(Include = "Id,Name,Gender,PhoneNumber,EmailAddress,Position,HireDate,Salary,EmployeeWebSite")]Employee employee)
- {
- if (ModelState.IsValid)
- {
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- return RedirectToAction("Index");
- }
- return View();
- }
- }
- }
Include Property of Bind Attribute
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create([Bind(Include = "Id,Gender,PhoneNumber,EmailAddress,Position,HireDate,Salary,EmployeeWebSite")]Employee employee)
- {
- if (ModelState.IsValid)
- {
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- return RedirectToAction("Index");
- }
- return View();
- }
Notice that we are using BIND attribute and specifying the properties that we want to include in model binding. Since the Name property is not specified in the INCLUDE list, it will be excluded from model binding.
Another way of excluding the exclude property
Exclude Property of Bind Attribute
- [HttpPost]
- [ValidateAntiForgeryToken]
- [ActionName("Create")]
- public ActionResult Create_Post([Bind(Exclude ="Name")]Employee employee)
- {
- if (ModelState.IsValid)
- {
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- return 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). Click on "Add.
Code for Index View
- @model IEnumerable<MvcBindAttribute_Demo.Models.Employee>
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>List of Employee</h2>
- <p>
- @Html.ActionLink("Create New","Create")
- </p>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>@Html.DisplayNameFor(m => m.Name)</th>
- <th>@Html.DisplayNameFor(m => m.Gender)</th>
- <th>@Html.DisplayNameFor(m => m.PhoneNumber)</th>
- <th>@Html.DisplayNameFor(m => m.EmailAddress)</th>
- <th>@Html.DisplayNameFor(m => m.Position)</th>
- <th>@Html.DisplayNameFor(m => m.HireDate)</th>
- <th>@Html.DisplayNameFor(m => m.Salary)</th>
- <th>@Html.DisplayNameFor(m => m.EmployeeWebSite)</th>
- </tr>
- </thead>
- @foreach (var employee in Model)
- {
- <tr>
- <td>@employee.Name</td>
- <td>@employee.Gender</td>
- <td>@employee.PhoneNumber</td>
- <td>@employee.EmailAddress</td>
- <td>@employee.Position</td>
- <td>@employee.HireDate</td>
- <td>@employee.Salary</td>
- <td>@employee.EmployeeWebSite</td>
- </tr>
- }
- </table>
Code for Create View
- @model MvcBindAttribute_Demo.Models.Employee
- @{
- ViewBag.Title = "Create";
- }
-
- <h3>Create New</h3>
- @using (Html.BeginForm())
- {
- <div class="row">
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.Name)
- @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Name)
- </div>
- </div>
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.Gender)
- @Html.DropDownList("Gender", new List<SelectListItem> {
- new SelectListItem { Text="Male",Value="Male"},
- new SelectListItem { Text="Female",Value="Female"}
- }, "Choose Gender", new { @class = "form-control" })
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.PhoneNumber)
- @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.PhoneNumber)
- </div>
- </div>
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.EmailAddress)
- @Html.TextBoxFor(m => m.EmailAddress, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.EmailAddress)
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.Position)
- @Html.TextBoxFor(m => m.Position, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Position)
- </div>
- </div>
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.HireDate)
- @Html.TextBoxFor(m => m.HireDate, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.HireDate)
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.Salary)
- @Html.TextBoxFor(m => m.Salary, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Salary)
- </div>
- </div>
- <div class="col-md-6">
- <div class="form-group">
- @Html.LabelFor(m => m.EmployeeWebSite)
- @Html.TextBoxFor(m => m.EmployeeWebSite, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.EmployeeWebSite)
- </div>
- </div>
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-primary">Submit</button>
- </div>
- }
Step 7
Build and run the project by pressing Ctrl+F5.