【问题标题】:How to get value from controller back to $.Ajax如何将控制器的价值返回给 $.Ajax
【发布时间】: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


【解决方案1】:

Result 是一个 javascript 对象,因此 alert 可以正常工作。如果你想提醒它的结构为 JSON 使用 JSON.stringify() 这样的方法:

alert(JSON.stringify(result));

如果您想访问您的 itemsCount,只需使用点或括号表示法:

alert(result.itemsCount);
alert(result['itemsCount']);

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多