簡體   English   中英

如何從控制器獲取價值回到$ .Ajax

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

我的設置:asp.net mvc Web應用程序

我在將值從控制器返回到$ .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]。 我瀏覽了所有相關文章,但找不到有效的解決方案。 有人可以提示我問題可能在哪里以及如何解決嗎? 預先感謝您,馬努

結果是一個javascript對象,因此警報可以正常工作。 如果要以JSON的形式警告其結構,請使用JSON.stringify()方法,如下所示:

alert(JSON.stringify(result));

如果要訪問itemsCount,只需使用點或括號表示法即可:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM