0

I'm trying to make a request to controller but it doesn't work. The first console.log() shows the correct id, so I think I passed it right in the html button. The id parameter is always 0 when it arrives at the controller.

That is the view's code:

function Delete(id) {
    console.log(id)

    if (!confirm("Vai excluir o produto mesmo chefe?")) {
        return;
    }

    $.ajax({
        url: "/Produtos/Delete",
        method: "POST",
        contentType: "application/json",
        dataType:"json",
        data: JSON.stringify({id : id}),
        success: function(response){
            alert(response.message)
        },
        error: function(error){
            alert(error.message)
        }
    });
}

This is the controller method:

[HttpPost]
public JsonResult Delete(int id)
{
    var produto =  _produtosRepository.GetById(id);

    if (produto == null)
    {
        return Json(new { success = false, message = $"Erro ao remover produto de id = {id}." });
    }
    
    _produtosRepository.Delete(produto);
    _produtosRepository.Save();

    return Json(new { success = true, message = "Produto deletado com sucesso." });
}

I tried to change the $.ajax call to fetch, but it doesn't work either. I don't know what do, could someone help me?

PS: I'm new to the ASP.NET MVC world, so I'm probably making a ridiculous mistake.

2 Answers 2

1

By default, the Id parameter in the controller action for ASP.NET MVC/API is treated as a route path.

You don't need to send the id as the request body. Instead, provide it in the route.

$.ajax({
  url: `/Produtos/Delete/${id}`,
  method: "POST",
  contentType: "application/json",
  dataType: "json",
  success: function(response){
    alert(response.message)
  },
  error: function(error){
    alert(error.message)
  }
});
1

The server-side Delete(int id) method expects a parameter named id, but the client-side code sends a JSON object { id: id }. ASP.NET Core's default model binder may not correctly map this JSON object to the method parameter because it expects form-urlencoded or query string data for simple parameters.

Use [FromBody] on the id parameter. This tells ASP.NET Core to bind the parameter from the JSON body of the request.

[HttpPost]
public JsonResult Delete([FromBody] int id)
{
    var produto = _produtosRepository.GetById(id);

    if (produto == null)
    {
        return Json(new { success = false, message = $"Erro ao remover produto de id = {id}." });
    }

    _produtosRepository.Delete(produto);
    _produtosRepository.Save();

    return Json(new { success = true, message = "Produto deletado com sucesso." });
}

If [FromBody] is not used, ASP.NET Core's model binder won't know how to extract the id from the JSON body, resulting in the default value 0.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.