user7739271
user7739271

Reputation:

When to use BindAttribute?

I'm learning asp.net mvc and wonder when we need to use BindAttribute.

The first case (using Bind):

Model:

public class Book
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Author { get; set; }
}

Controller:

public IActionResult Create([Bind(nameof(Book.Name), nameof(Book.Author))] Book model)
{
    return Ok();
}

The book Id would be generated on server side. So, client side has nothing to do with it, every actions try to change/make the id is prevented.

The second case (not using Bind):

Model:

public class BookViewModel
{
    public string Name { get; set; }

    public string Author { get; set; }
}

Controller:

public IActionResult Create(BookViewModel model)
{
    return Ok();
}

Because the second model doesn't contain Id property, we don't need to prevent from creating or changing.

I prefer the second. It's easy to manage model.

Is there a case we must use Bind attribute?

Upvotes: 10

Views: 10141

Answers (2)

Vlado Pandžić
Vlado Pandžić

Reputation: 5048

We use bind when we want that some properties of complex property are ignored when received on server. It could be for safety or other reasons.

When this action is executed the MVC model binder will use the request parameters to populate the user parameter's properties, as you may already know. However, the Bind attribute tells the model binder to only populate properties with names specified.

So in this case only the Username, FullName and Email properties will be populated. All others will be ignored.

See here for more details: http://ittecture.wordpress.com/2009/05/01/tip-of-the-day-199-asp-net-mvc-defining-model-binding-explicitly/

If you have situation when you only have to ignore one parametar from binding you could use Exclude property:

[Exclude] 
public Entity Name {get; set;}

Upvotes: 6

piyush sanadhya
piyush sanadhya

Reputation: 464

Bind is used to increase security and unauthorized data to be posted on server . In your model class , suppose you have content property also. if the content property is not needed in the future. Then it would be difficult for you to remove all the occurrences of that property. Here you can use bind property like this

[Bind(exclude="content")] 

or you can bind only selected properties to be posted on server by including the properties like this

 public ActionResult create([Bind(Include = "Name,Author")] Modelclass modelclass)
{
//Do something here
}

You can learn more about it here

Second approach is more suitable instead writing all the properties and bind them but there are some situations where you must bind user like you have a roles property or IsAdmin property in your model then you might not want that user somehow posts the IsAdmin or roles properties to the server . That's where you can use Bind attribute

Upvotes: 3

Related Questions