How to use Bind Prefix?

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.

Leave a Comment