Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Bind Prefix?

Say if I had this table in my db: Product

It had

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?

like image 585
chobo2 Avatar asked Aug 23 '09 01:08

chobo2


People also ask

What is bind property in C#?

The Binding class is used to bind a property of a control with the property of an object. For creating a Binding object, the developer must specify the property of the control, the data source, and the table field to which the given property will be bound.

What is bind attribute in MVC?

Bind AttributeThe [Bind] attribute will let you specify the exact properties of a model should include or exclude in binding. In the following example, the Edit() action method will only bind StudentId and StudentName properties of the Student model class. Example: Binding Parameters.

How do you bind a model to view in MVC?

Step 1: Open the VS 2019 and select the ASP.NET core web application. Step 2: Select the template of the web application (MVC). Step 3: Go to the home controller and student basic type binding. Step 5: Now, press f5 and run the solution.


1 Answers

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.

like image 190
John Foster Avatar answered Sep 24 '22 19:09

John Foster