简体   繁体   English

如何从控制器获取价值回到$ .Ajax

[英]How to get value from controller back to $.Ajax

My setup: asp.net mvc web app 我的设置:asp.net mvc Web应用程序

I am having trouble getting a value from a controller back to the $.Ajax call (see below). 我在将值从控制器返回到$ .Ajax调用时遇到麻烦(请参见下文)。 The controller deletes a record in a database and counts some other records. 控制器删除数据库中的一条记录,并对其他一些记录进行计数。

$.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();
    }
}

The ajax call and the controller work properly, however when I try to use the returned value in the success function, the alert(result) gives [object object]. Ajax调用和控制器正常工作,但是当我尝试在成功函数中使用返回值时,alert(result)给出[object object]。 I have looked through all related posts, but could not find a solution that worked. 我浏览了所有相关文章,但找不到有效的解决方案。 Could someone give me a hint where the problem could be and how to make it work? 有人可以提示我问题可能在哪里以及如何解决吗? Thank you in advance and regards, Manu 预先感谢您,马努

Result is a javascript object so alert works properly. 结果是一个javascript对象,因此警报可以正常工作。 If you want to alert it's structure as JSON use JSON.stringify() method like this: 如果要以JSON的形式警告其结构,请使用JSON.stringify()方法,如下所示:

alert(JSON.stringify(result));

If you want to access your itemsCount, just use dot or bracket notation: 如果要访问itemsCount,只需使用点或括号表示法即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM