Bind Attribute In ASP.NET MVC

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.
 
Bind Attribute In ASP.NET MVC
 
Step 3
 
Select "empty" template, check on MVC checkbox, and click OK.
 
Bind Attribute 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.
 
Bind Attribute 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".
 
Bind Attribute In ASP.NET MVC
 
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
 
Bind Attribute 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".
 
Bind Attribute 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".
 
Bind Attribute 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".
 
Bind Attribute In ASP.NET MVC
 
Entity Framework gets added and the respective class gets generated under the Models folder.
 
Bind Attribute In ASP.NET MVC
 
Employee Class
  1. namespace MvcBindAttribute_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.ComponentModel.DataAnnotations;  
  6.     public partial class Employee  
  7.     {  
  8.         public int Id { getset; }  
  9.    
  10.         [Required(ErrorMessage ="Please enter name")]  
  11.         public string Name { getset; }  
  12.    
  13.         [Required(ErrorMessage = "Please choose gender")]  
  14.         public string Gender { getset; }  
  15.    
  16.         [Required(ErrorMessage = "Please enter phone number")]  
  17.         [Display(Name ="Phone Number")]  
  18.         [Phone]  
  19.         public string PhoneNumber { getset; }  
  20.    
  21.         [Required(ErrorMessage = "Please enter email address")]  
  22.         [Display(Name ="Email Address")]  
  23.         [EmailAddress]  
  24.         public string EmailAddress { getset; }  
  25.    
  26.         [Required(ErrorMessage = "Please enter position")]  
  27.         public string Position { getset; }  
  28.    
  29.         [Required(ErrorMessage = "Please enter hire date")]  
  30.         [Display(Name ="Hire date")]  
  31.         public Nullable<System.DateTime> HireDate { getset; }  
  32.    
  33.         [Required(ErrorMessage = "Please enter salary")]  
  34.         [DataType(DataType.Currency)]  
  35.         public Nullable<int> Salary { getset; }  
  36.    
  37.         [Required(ErrorMessage = "Please enter website")]  
  38.         [Display(Name ="Personal Website")]  
  39.         [Url]  
  40.         public string EmployeeWebSite { getset; }  
  41.     }  
  42. }  
Step 5

Right-click the Controllers folder and add a controller.
 
Bind Attribute In ASP.NET MVC
 
A window will appear. Choose MVC5 Controller-Empty and click "Add".
 
Bind Attribute 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.
 
Bind Attribute In ASP.NET MVC
 
The complete code for Home Controller is given below.
  1. using MvcBindAttribute_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 MvcBindAttribute_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.         [HttpGet]  
  21.         public ActionResult Create()  
  22.         {  
  23.             return View();  
  24.         }  
  25.    
  26.         [HttpPost]  
  27.         [ValidateAntiForgeryToken]  
  28.         public ActionResult Create([Bind(Include = "Id,Name,Gender,PhoneNumber,EmailAddress,Position,HireDate,Salary,EmployeeWebSite")]Employee employee)  
  29.         {  
  30.             if (ModelState.IsValid)  
  31.             {  
  32.                 _dbContext.Employees.Add(employee);  
  33.                 _dbContext.SaveChanges();  
  34.                 return RedirectToAction("Index");  
  35.             }  
  36.             return View();  
  37.         }  
  38.     }  
  39. }  
Include Property of Bind Attribute
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Create([Bind(Include = "Id,Gender,PhoneNumber,EmailAddress,Position,HireDate,Salary,EmployeeWebSite")]Employee employee)  
  4. {  
  5.     if (ModelState.IsValid)  
  6.     {
  7.         _dbContext.Employees.Add(employee);  
  8.         _dbContext.SaveChanges();  
  9.         return RedirectToAction("Index");  
  10.     }  
  11.     return View();  
  12. }  
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
  1. [HttpPost]  
  2.         [ValidateAntiForgeryToken]  
  3.         [ActionName("Create")]  
  4.         public ActionResult Create_Post([Bind(Exclude ="Name")]Employee employee)  
  5.         {  
  6.             if (ModelState.IsValid)  
  7.             {  
  8.                 _dbContext.Employees.Add(employee);  
  9.                 _dbContext.SaveChanges();  
  10.                 return RedirectToAction("Index");  
  11.             }  
  12.             return View();  
  13.         }  
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.
 
Bind Attribute In ASP.NET MVC
 
Code for Index View
  1. @model IEnumerable<MvcBindAttribute_Demo.Models.Employee>  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.    
  6. <h2>List of Employee</h2>  
  7. <p>  
  8.     @Html.ActionLink("Create New","Create")  
  9. </p>  
  10. <table class="table table-bordered">  
  11.     <thead>  
  12.         <tr>  
  13.             <th>@Html.DisplayNameFor(m => m.Name)</th>  
  14.             <th>@Html.DisplayNameFor(m => m.Gender)</th>  
  15.             <th>@Html.DisplayNameFor(m => m.PhoneNumber)</th>  
  16.             <th>@Html.DisplayNameFor(m => m.EmailAddress)</th>  
  17.             <th>@Html.DisplayNameFor(m => m.Position)</th>  
  18.             <th>@Html.DisplayNameFor(m => m.HireDate)</th>  
  19.             <th>@Html.DisplayNameFor(m => m.Salary)</th>  
  20.             <th>@Html.DisplayNameFor(m => m.EmployeeWebSite)</th>  
  21.         </tr>  
  22.     </thead>  
  23.     @foreach (var employee in Model)  
  24.     {  
  25.         <tr>  
  26.             <td>@employee.Name</td>  
  27.             <td>@employee.Gender</td>  
  28.             <td>@employee.PhoneNumber</td>  
  29.             <td>@employee.EmailAddress</td>  
  30.             <td>@employee.Position</td>  
  31.             <td>@employee.HireDate</td>  
  32.             <td>@employee.Salary</td>  
  33.             <td>@employee.EmployeeWebSite</td>  
  34.         </tr>  
  35.     }  
  36. </table>  
Code for Create View
 
Bind Attribute In ASP.NET MVC
  1. @model MvcBindAttribute_Demo.Models.Employee  
  2. @{  
  3.     ViewBag.Title = "Create";  
  4. }  
  5.    
  6. <h3>Create New</h3>  
  7. @using (Html.BeginForm())  
  8. {  
  9.     <div class="row">  
  10.         <div class="col-md-6">  
  11.             <div class="form-group">  
  12.                 @Html.LabelFor(m => m.Name)  
  13.                 @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
  14.                 @Html.ValidationMessageFor(m => m.Name)  
  15.             </div>          
  16.         </div>  
  17.         <div class="col-md-6">  
  18.             <div class="form-group">  
  19.                 @Html.LabelFor(m => m.Gender)  
  20.                 @Html.DropDownList("Gender"new List<SelectListItem> {  
  21.                 new SelectListItem { Text="Male",Value="Male"},  
  22.                 new SelectListItem { Text="Female",Value="Female"}  
  23.                 }, "Choose Gender"new { @class = "form-control" })  
  24.             </div>              
  25.         </div>  
  26.     </div>  
  27.     <div class="row">  
  28.         <div class="col-md-6">  
  29.             <div class="form-group">  
  30.                 @Html.LabelFor(m => m.PhoneNumber)  
  31.                 @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control" })  
  32.                 @Html.ValidationMessageFor(m => m.PhoneNumber)  
  33.             </div>           
  34.         </div>  
  35.         <div class="col-md-6">  
  36.             <div class="form-group">  
  37.                 @Html.LabelFor(m => m.EmailAddress)  
  38.                 @Html.TextBoxFor(m => m.EmailAddress, new { @class = "form-control" })  
  39.                 @Html.ValidationMessageFor(m => m.EmailAddress)  
  40.             </div>          
  41.         </div>  
  42.     </div>  
  43.     <div class="row">  
  44.         <div class="col-md-6">  
  45.             <div class="form-group">  
  46.                 @Html.LabelFor(m => m.Position)  
  47.                 @Html.TextBoxFor(m => m.Position, new { @class = "form-control" })  
  48.                 @Html.ValidationMessageFor(m => m.Position)  
  49.             </div>             
  50.         </div>  
  51.         <div class="col-md-6">  
  52.             <div class="form-group">  
  53.                 @Html.LabelFor(m => m.HireDate)  
  54.                 @Html.TextBoxFor(m => m.HireDate, new { @class = "form-control" })  
  55.                 @Html.ValidationMessageFor(m => m.HireDate)  
  56.             </div>            
  57.         </div>  
  58.     </div>  
  59.     <div class="row">  
  60.         <div class="col-md-6">  
  61.             <div class="form-group">  
  62.                 @Html.LabelFor(m => m.Salary)  
  63.                 @Html.TextBoxFor(m => m.Salary, new { @class = "form-control" })  
  64.                 @Html.ValidationMessageFor(m => m.Salary)  
  65.             </div>              
  66.         </div>  
  67.         <div class="col-md-6">  
  68.             <div class="form-group">  
  69.                 @Html.LabelFor(m => m.EmployeeWebSite)  
  70.                 @Html.TextBoxFor(m => m.EmployeeWebSite, new { @class = "form-control" })  
  71.                 @Html.ValidationMessageFor(m => m.EmployeeWebSite)  
  72.             </div>          
  73.         </div>  
  74.     </div>  
  75.     <div class="form-group">  
  76.         <button type="submit" class="btn btn-primary">Submit</button>  
  77.     </div>    
  78. }  
Step 7
 
Build and run the project by pressing Ctrl+F5.
 
Bind Attribute In ASP.NET MVC
 
Bind Attribute In ASP.NET MVC


Similar Articles