我正在尝试向控制器发出请求,但它不起作用。第一个
console.log()
显示了正确的 id,所以我认为我在 html 按钮中正确传递了它。 id
参数到达控制器时始终为0。
这是视图的代码:
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)
}
});
}
这是控制器方法:
[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." });
}
我尝试将
$.ajax
调用更改为 fetch,但它也不起作用。我不知道该怎么办,有人可以帮助我吗?
PS:我是 ASP.NET MVC 世界的新手,所以我可能犯了一个可笑的错误。
默认情况下,ASP.NET MVC/API 控制器操作中的
Id
参数被视为路由路径。
您不需要发送
id
作为请求正文。相反,请在路线中提供它。
$.ajax({
url: `/Produtos/Delete/${id}`,
method: "POST",
contentType: "application/json",
dataType: "json",
success: function(response){
alert(response.message)
},
error: function(error){
alert(error.message)
}
});
服务器端Delete(int id)方法需要一个名为id的参数,但客户端代码发送一个JSON对象{id:id}。 ASP.NET Core 的默认模型绑定器可能无法正确将此 JSON 对象映射到方法参数,因为它需要表单 urlencoded 或查询字符串数据作为简单参数。
在 id 参数上使用 [FromBody]。这告诉 ASP.NET Core 绑定请求 JSON 正文中的参数。
[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." });
}
如果不使用 [FromBody],ASP.NET Core 的模型绑定器将不知道如何从 JSON 主体中提取 id,从而导致默认值 0。