What is Attributes ?

Attributes are classes that allow you to add additional information to elements of your class structure.

What is Bind Attributes ?

In ASP.NET MVC View that accepts user input and post information to a server. Bind Attribute allow  an option to restrict the properties(ie., model) that are allowed to be bound automatically.

Where can we use Bind Attributes ? :

Scenario :

For example we having model/properties for binding the EMP DETAILS as shown below

Model :

public class EmployeeDetail
{
public string EmpName {get;set;}
public string EmpAddress {get;set;}
public string Department {get;set;}
}

From above some employee have rights to enter Department but some employee not have such rights to add Department.  In such scenario we can easily do it form level by hiding the Department Details from the page/Separate page, In this scenario we can use Bind Attribute to eliminate this property to update in Model/Property/DB.

Example : We can achieve this in two ways

1) Handel in Action Level

2) Handel in Model Level

Let we discuss about Action Level :

In Action Level, we will restrict the property while receiving to method ( it will not filter in model)

controller :

In controller we can restrict particular property (department) as shown below

public class EmployeeDetailController : Controller
{

[HttpPost]
public JsonResult Save([Bind(Exclude = “Department”)] EmployeeDetail emp)
{
return Json(string.Format(“EMP DETAIL”, emp));
}
}

view

@using (Html.BeginForm(“Save”, “EmployeeDetail”, FormMethod.Post, new
{
@id = “saveEmpDetails”
}))
{
@Html.TextBoxFor(m => m.EmpName)
@Html.TextBoxFor(m => m.EmpAddress)
@Html.TextBoxFor(m => m.Department)
<input type=”submit” value=”Insert” name=”Insertaction”/>
}

OUTPUT :

Bind 1

Click insert button to view in debug mode, as shown In below the model restrict to bind the value for the Department.

Bind 2
Let we discuss about Model Level Restriction :

We can handel in Model as shown below

[Bind(Exclude = “Department”)]
public class EmployeeDetail
{
public string EmpName{get;set;}
public string EmpAddress{get;set;}
public string Department{get;set;}
}


NOTE :

  • Attribute will be executed before the action
  •  If we place [Bind(Exclude = “Department”)] above the class it will exclude Department from other class inside the particular Model page
  •  If we place it inside the class it will applicable to particular class