What is the purpose of the "[Bind("ID,Title,Releasedate,Genre,Price")]" feature in a method?

Asked

Viewed 106 times

2

I am creating a project in ASP.NET Core MVC for learning purposes. In a certain part of the Microsoft guide when the technique of scaffold to generate the controller and the views corresponding to the actions of controller, I came across an instruction in some methods that left me doubtful in well confused.

See below the method Create as an example:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
    if (ModelState.IsValid)
    {
        _context.Add(movie);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(movie);
}

See the statement before the parameter declaration movie. It is at this point that my doubt arose and left me confused.

Doubts

  1. What kind of characteristic is instruction [Bind("ID,Title,ReleaseDate,Genre,Price")] passed at signature of the Create method?
  2. What would be the purpose of this feature when used in a method?
  • 2

    I know it serves to define which attributes of the object should be passed in Httppost, similarly there is another instruction to delete attributes from Bind done during the Post on the object. I do not have more information to formulate a decent answer, so I leave it as a comment only =] https://msdn.microsoft.com/en-us/library/system.web.mvc.bindattribute(v=vs.118). aspx

1 answer

2


What kind of feature is the [Bind("ID,Title,Releasedate,Genre,Price")] statement passed in the Create method signature?

Are attributes. Can be used in other parts of the code.

What would be the purpose of this feature when used in a method?

It is a way to define metadata for the request. This can be used by the compiler, by framework general (.NET), the framework specific (e.g., ASP.NET) or even your own application.

This information can be obtained with reflection and used in the most convenient way.

In this case ASP.NET Core takes the information there and maps it to the object, then the strings received by HTTP with the names cited there will be used to compose the object movie. The framework know how to do this, you just need to know how to use the attribute to indicate what it should do.

It’s even a security measure against undue data injection.

Is a more declarative form of programming which is useful in some cases to reduce the Boiler Plate (code to do boring, repetitive operations, just to solve something before you do what you really need, it takes care of a necessary bustle, but that does not add anything specific to the solution).

Another example of use.

  • This also serves to protect the controller against overpost.

  • No doubt.....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.