Ask your technical questions on forums or here :
ASP.NET or MVC | C# | Windows Phone
Microsoft Technology Journals by Abhimanyu K Vatsa

16 Oct 2012

MVC Bind Attribute like [Bind(Exclude = "Name")] or [Bind(Include = "Address, Payment, EmailID")]

When we have an ASP.NET MVC View that accepts user input and posts those inputs to a server we have the option to use the built-in Model-binding features to provide more control and security, we can restrict the properties that are allowed to be bound automatically.

Let's look at my demo mode:

By default any "View" or UI which is associated with the above model can "Post" the data to the server for each and every property. Please Note: In case "StudentId" is the primary key and it has the auto-increment property at DB level then the DB Server will not accept your any data by "Post" for this property.

What if, at any point of time, management demands that you to stop accepting an "Address" property, either by new record entry or by editing an existing record, what will you do? What if you even don't know how many "Views" or UI are connected to this model. Then, fulfilling such a demand will be a headache for you.

There may be many ways to do this, and I would enjoy hearing your comments; please go ahead and post your input.

Now, let's talk about fundda (technique):

Note: Use a namespace "using System.Web.Mvc" to enable this feature.

In the above image, I have added "[Bind(Exclude = "Address")]" on the top of all classes; in other words, this bind attribute will exclude an "Address" property from being posted to server. In the same way, to increase the security we can use a "[Bind(Include = "Name, Payment, EmailID")]" attribute. I'm even using the attribute at the very top, so each and every model class will follow this attribute. In case you want this for any one model class, do that like this:

Now, you don't need to modify your existing "View" or UI, this works silently. Look at the image given below; the user is trying to send "Address" information but our model class eliminated "Address" information from the "Post" packet.

That's cool. I hope this helps you. Thanks.

Comment using Google Services (2 comments):