What am I doing with this method?

2

I have the following method:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Criar([Bind(Include = "CategoriaId,Nome")] Categoria categoria)
{
    if (ModelState.IsValid)
    {
        categoria.CategoriaId = Guid.NewGuid();
        db.Categorias.Add(categoria);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    return View(categoria);
}

I would like an explanation about it, what I'm doing in the constructor when I use ([Bind(Include = "CategoriaId,Nome")] What exactly does BIND mean?

    
asked by anonymous 30.11.2016 / 20:25

1 answer

2

Imagine that your Categoria object has a ind_exclusao field, in addition to the CategoriaId and Nome fields.

Imagine you have view to edit a category where you can rename it.

This view has a imput with Category Name ...

When this view does a POST it sends the data of the category in body of request to the server.

The server in turn converts this data into an object Categoria , which is what arrives at its Controller .

This is the default working ...

In the case of edit above it can not exclude, that is, the object ind_exclusao always arrives falso .

If someone simulates a POST on your server, not using your view, and places in the body of request a Category object with id XXX, name YYYY, and exclude indicator True its Controller knows if you are getting a POST from the view or not) will convert the body data into your Category object entering the controller.

This conversion of the body data of POST into the Object that enters the Controller is called BIND .

When you put [Bind(Include = "CategoriaId,Nome")] in the Controller method signature, you force the server to ONLY get the CategoriaId and Nome of the POST body and convert it to the object. In this case, if there is an exclusion indicator in the body it will be ignored.

This is a safety measure and it is advisable to use it.

If you have any questions, please let me know more about the answer.

    
30.11.2016 / 20:35