【发布时间】:2018-02-20 19:35:13
【问题描述】:
我的设置:asp.net mvc web app
我无法从控制器获取值返回给 $.Ajax 调用(见下文)。控制器删除数据库中的一条记录并统计其他一些记录。
$.ajax({
type: "POST",
url: actions.action.RemoveItem + "?id=" + dataId,
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
success: function (result) {
alert(result);
},
error: function (result) {
alert("Error");
}});
[HttpPost]
public JsonResult RemoveItem(int id)
{
... delete a record in the db
itemsCount = .... counts of some other records in the db
if (deletedRecord.id != null)
{
return Json(new { itemsCount });
}
else
{
return JsonError();
}
}
ajax 调用和控制器正常工作,但是当我尝试在成功函数中使用返回值时,alert(result) 给出 [object object]。 我浏览了所有相关的帖子,但找不到有效的解决方案。有人可以给我一个提示问题可能出在哪里以及如何使其工作的提示吗? 提前谢谢你和问候,Manu
【问题讨论】:
-
如果您尝试
console.log(result);而不是警报,您将获得更多关于您实际返回的提示。在浏览器控制台中查找输出 (F12)。你的结果是一个 json 对象。 -
尝试像
Json(itemCount)一样返回itemCount,如果您的itemCount有价值,它应该可以工作。 -
因为您要返回一个对象(具有名为
itemCount的属性)。在脚本中使用alert(result.itemsCount);或仅返回return Json(itemsCount);(并删除您毫无意义的contentType: "application/json; charset=utf-8",和traditional: true,选项-您的请求不会在正文中发送任何内容)
标签: c# jquery asp.net-mvc asp.net-ajax