In this article, I am going to discuss Bind Attribute in ASP.NET MVC Application to Include and Exclude properties in Model Binding. Please read our previous article where we discussed Unintended Updates in the ASP.NET MVC application. When we want to include or exclude properties from model binding then we need to use the Bind Attribute in ASP.NET MVC application. We are also going to work with the same example that we worked on in our previous article. As part of this article, we are going to discuss the following pointers.
- Understanding the Bind Attribute class.
- Including Model Properties using Bind Attributes.
- Excluding Model Properties using Bind Attribute.
Understanding the Bind Attribute in ASP.NET MVC:
Let us first have a look at the definition of the BindAttribute class in the ASP.NET MVC Framework. As you can see the BindAttribute class is inherited from the Attribute class and also contain some properties i.e. Exclude, Include, Prefix, and IsPropertyAllowed method.
- Exclude: The Exclude property is used to get or set a comma-delimited list of property names for which binding is not allowed.
- Include: The Include property is used to get or set a comma-delimited list of property names for which binding is allowed.
- Prefix: The Prefix property is used to gets or sets the prefix to use when markup is rendered for binding to an action argument or to a model property.
- IsPropertyAllowed: The IsPropertyAllowed method is used to determines whether the specified property is allowed. It returns true if the specified property is allowed; otherwise, false.
Let us understand how to use the Bind Attribute in ASP.NET MVC Application with an example. First, modify the “Edit_Post()†action method of EmployeeController.cs as shown below.
As you can see in the above action code, using the “BIND†attribute we are specifying the properties that we want to include in our model binding using the Include property of BindAttribute class. As the “Name†property of the Employee model is not specified in the Include list, so it will be excluded from model binding. Now, if you generate a post request using fiddler as we did in the previous session, the “Name†property of the “Employee†object will not be updated.
Using the Exclude Property of BindAttribute class in ASP.NET MVC:
You can also achieve the same thing using the Exclude property of the Bind Attribute class in the ASP.NET MVC Application. Here, you need to specify the properties which you want to exclude from model binding as shown below in the below code.
As you can see in the above code, we specify the Name property in the Exclude list of the Bind Attribute class. So, here the Name property will be excluded from model binding.