asp.net-mvc - net - what is[bind(prefix=
How to use Bind Prefix? (1)
Say if I had this table in my db: Product
ProductId ProductName ProductType
Now for whatever reason I can't name my textboxes ProductName and ProductType so now my View Method would look like this
public ViewResult Test([Bind(Exclude ="ProductId")] Product)
So now through my playing around nothing would be matched in this product since they have different names.
So I guess this is where Prefix would come in but I don't know how to use it. Nor how do I use it and Exclude at the same time.
Can someone give me an example?
The prefix is used as follows if in your view you have...
<select name="p.ProductType">....</select> <input type="text" name="p.ProductName" />
You can bind the incoming form to an instance of your model by doing something like
public ActionResult([Bind(Prefix="p")]Product product)
You should note that MVC would do this automatically for you if you named your method argument p.
The prefix can be very useful if you're trying to bind multiple entities at the same time (e.g. two name fields).
To use the exclude binding to certain Properties (i.e. avoid people passing in ProductIds in a forged form) just set the property names to exclude
public ActionResult([Bind(Prefix="p", Exclude="ProductId")]Product product)
This will ensure that the ProductId on your entity never gets set.
If you want to bind two completely different field names e.g. Type to ProductType you can look at custom model binding or just grabbing the field out the FormCollection yourself.