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.