What am I doing with this method?

Asked

Viewed 52 times

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’d like an explanation about him, what I’m doing in the builder when I use the ([Bind(Include = "CategoriaId,Nome")] What exactly does the BIND ?

  • 5

    I recommend visualizing this question that has very complete answer from the mustache

  • 1

    See if that question linked above answers what you want

  • Okay, I must remove the one I made ?

  • for now you don’t need it, maybe you won’t need it. Maybe your question is different.

1 answer

2


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

Imagine you have a view to edit a category where you can change its name.

That one view has a imput with the category name...

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

The server in turn converts this data into an object Categoria, which is what comes in your Controller.

This is the working standard...

In the case of the above edit it cannot delete, ie the object ind_exclusao always comes falso.

If someone fakes one POST on your server, not using your view, and put in the body of request a Category object with id XXX, name YYYY and exclusion indicator True your Controller (that does not know if you are receiving a POST from the view or not) will convert the body data into your Category object entering the controller.

Such conversion of the POST in the Object entering the Controller is called BIND.

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

This is a safety measure and it is advisable to be used.

If you have any questions, ask me what I best detail the answer.

Browser other questions tagged

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