How To Use Bind Attribute In Asp.Net MVC
In this article we will understand how to use Bind Attribute in Asp.Net MVC By Sagar Jaybhay. Also we will Understand Including And Excluding Properties In Model Binding.
Bind Attribute In Asp.Net MVC
In a previous article or aove we understand how to create IncludeList and Exclude List but there is another way to do the same functionality by using Bind class. Bind class has several overloaded methods by using this ou can Include and Exclude several properties from the strongly typed model. Below is the code for that.
[HttpPost] // Bind Function
public ActionResult Edit([Bind(Include = "EmpID,EmpGender,EmpSalary, EmpCity, EmpEmail, DepartmentID")]Employee employee)
var emp = new BusinessLogic.Business().GetEmployee(employee.EmpID.ToString());
employee.EmpName = emp.EmpName;
// UpdateModel(emp, new string[] "EmpSalary", "EmpGender", "EmpCity", "EmpEmail", "DepartmentID" );
if (ModelState.IsValid)
new BusinessLogic.Business().UpdateEmployee(employee);
return RedirectToAction("DisplayCompleteEmployee");
return View(employee);
Including And Excluding Properties from Model Binding Using Interfaces in Asp.Net MVC
We need to create an interface first for this. As we are using Employee class as our model then we need to create an Iemployee interface that contains some properties which we needed and which you don’t want you can not mention in your interface.
interface Iemployee
int EmpID get; set;
double EmpSalary get; set;
string EmpGender get; set;
string EmpCity get; set;
string EmpEmail get; set;
To pass our model object with an interface you need to implement this interface in our Employee class like shown below
public class Employee: Iemployee // Here implementing Iemployee interface for the UpdateModel function using Interfaces
[DisplayName("ID")]
public int EmpID get; set;
// [Required]
[DisplayName("Name")]
public string EmpName get; set;
[Required]
[DisplayName("Salary")]
public double EmpSalary get; set;
[Required]
[DisplayName("Gender")]
public string EmpGender get; set;
[DisplayName("City")]
[Required]
public string EmpCity get; set;
[Required]
[DisplayName("Email")]
public string EmpEmail get; set;
[Required]
public int DepartmentID get; set;
Now our controller method looks like below
[HttpPost] // Bind Atrtibute Function
public ActionResult Edit(int EmpID)
var emp = new BusinessLogic.Business().GetEmployee(EmpID.ToString());
UpdateModel<Iemployee>(emp);
if (ModelState.IsValid)
new BusinessLogic.Business().UpdateEmployee(emp);
return RedirectToAction("DisplayCompleteEmployee");
return View(emp);
GitHub :- https://github.com/Sagar-Jaybhay/MVC5
Comments
Post a Comment