Id value is not changing in ASP.NET MVC 5

Asked

Viewed 20 times

0

I am creating a CRUD in ASP.NET in my project, however, started to give a problem. When I try to delete a Product, it passes the totally different Id to the other View, an Id that does not match the assigned value. Because of this, I cannot delete the desired product. I have tried changing the Id by View, as shown in the following code

<a href="@Url.Action("Edit", "Produto", new { id=item.idProduto })" 
    class="btn btn-warning btn-sm active">
    Editar
</a>
<a href="@Url.Action("Delete", "Produto", new { id=item.idProduto })" 
    class="btn btn-danger btn-sm active">
    Excluir
</a>

But nothing has changed, it continues with the same problem. This code is located in the View that lists all the data of the Product. Actionresult code:

public ActionResult Delete(int id)
{
    var objproduto = new Produto();
    objproduto.idProduto = id.ToString();
    return View(objproduto);
}

// POST: Categoria/Delete/5
[HttpPost]
public ActionResult Delete(Produto produto)
{
    if (produto.idProduto != null)
    {
        var objproduto = new Produto();
        objproduto.DeleteProduto(produto);

        return RedirectToAction("Details");
    }

    return View();
}

How can I solve this problem?

  • Good evening Leo, is your View typed? Where does the "item.idProduct" come from? Another observation is... The advisable is that the id is an integer and not a string. Because then the bank can auto-increment the value automatically. Try to change that too. I don’t think this is a mistake, but it’s good practice.

  • Yes, it is a typed View. item.idProduct comes from the Model itself, where item would be the variable in Model. Yes, actually I also consider a much better integer to represent an identification, I will start using instead of a String. You know what the real problem is? It is that he is bringing the Id of another data, which in this case is the Idcategoria, it is as if he simply ignored the Idproduto and took only the Idcategoria

  • Your face code already worries me where the business layer is mixed with message passing, methods in classes that should only send message ... !!! Finally has to put all classes involved, but, face your code reveals great problems

No answers

Browser other questions tagged

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