Home » ASP » ASP.MVC » Asp.Net Bind Attribute for your Controller

Asp.Net Bind Attribute for your Controller

Asp.Net MVC gives you the possibility to control the flow of information between Html Form and .Net Controller. It is possible to have model classes that are bound to Html Forms but without desire them to be sent back from forms.

A simple use case can be that we have a user model class that has a “IsAdmin” property. The user class can be bound to an html form, and instead of having a EditorFor for this property, a simple DisplayFor is set. An hacker could create an hidden field inside the form with the name “IsAdmin” and send “True”. Once the form is submitted, the “IsAdmin” will be bound because the Model Binding maps every form name fields to properties of the class.

Asp.Net MVC lets you specify which properties that is allowed to be bound from a form OR which properties that should never be read from the HTML form. This is also called white listing properties or black listing properties.

To demonstrate you this feature, I have create a simple model class that has 5 properties which can be nullable. These properties are all bound to an Html Form. For the purpose of this exercise, they are all bound to text boxes. In fact, as mentioned, some could not have been bound to a editable control and some one could forge the post later on. The first example send all properties back to the controller, and the controller set all information info a view bag and show again the view. The view should be filled up with the view bag information.

Here is all steps.

If property1 and property2 should not be bound from the form, we need to blacklist them. To tell the Asp.Net MVC Model Binding to not use properties, the attribute Bind must be used with the property Exclude.

In this screenshot, you can see that the property 1 and property 2 is not inside the view bag. The reason is that the model binder does not set the value to the model which kept the value to the default one. Since the model are nullable int for all properties, the default value remain NULL.


Finally, another scenario is available to white list properties. This option is interesting if you do have a lot of properties to exclude. Instead of having to specify a lot of properties in the exclude field, you just need to specify few in the Include field.


You can everything discussed in this blog post by download my Asp.Net MVC Bind project on GitHub

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

One Response so far.

  1. Stuart D says:

    Your mode of explaining all in this post is genuinely pleasant,
    every one be able to simply understand it, Thanks a lot.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.