I’m trying to make a request to controller but it doesn’t work. The fist console.log() shows the right 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)
}
});
}
That is the controller’s 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 to fetch but it doesn’t worked too. I don’t know what do, could someone help me?
PS: I’m new at this mvc world, so I’m probably making a ridiculous mistake haha.
2
Answers
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.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.
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.