Bind attribute in ASP.NET MVC

Bind Attribute in ASP.NET MVC

In this article, we will discuss include and exclude properties from model binding using the Bind Attribute in ASP.NET MVC application. In our previous article, we have discussed how to include and exclude properties from model binding by passing a string array to UpdateModel() method. There is another way to do the same thing using the “Bind” attribute. 

We are going to work with the same example that we started in our previous article.

Modify “Edit_Post()” controller action method that is present in “EmployeeController.cs” file, as shown below.

[HttpPost]
[ActionName("Edit")]
public ActionResult Edit_Post([Bind(Include = "Id, Gender, City, Salary, DateOfBirth")] Employee employee)
{
    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
    employee.Name = employeeBusinessLayer.GetAllEmployess().Single(x => x.ID == employee.ID).Name;

    if (ModelState.IsValid)
    {
        employeeBusinessLayer.UpdateEmmployee(employee);
        return RedirectToAction("Index");
    }
    return View(employee);
}

Notice that we are using “BIND” attribute and specifying the properties that we want to include in model binding. Since “Name” property is not specified in the INCLUDE list it will be excluded from model binding.

public ActionResult Edit_Post([Bind(Include = “Id, Gender, City, Salary, DateOfBirth”)] Employee employee)

At this point run the application and navigate to “http://localhost/MVC_DEMO/Employee/Edit/1”.

So, if we were to generate a post request using fiddler as we did in the previous session, “Name” property of the “Employee” object will not be updated.

Alternatively, to exclude properties from binding we can specify the exclude list using Bind attribute as shown below. 

[HttpPost]
[ActionName("Edit")]
public ActionResult Edit_Post([Bind(Exclude = "Name")] Employee employee)
{
    // Rest of the method implementation remains the same
}

In the next article, I will explain include and exclude properties from model binding using interface in ASP.NET MVC application

SUMMARY

In this article, I try to explain how to use Bind attribute to include and exclude properties from model binding in ASP.NET MVC application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *