0

我将一些值传递给 MVC 控制器,它正在返回 json 值。现在的问题是控制器端,值正确返回但是当我在 jquery 中检查它时,它显示未定义的数据。

控制器代码:

[HttpPost]
[Authorize]
public ActionResult DeleteServices(List<Int32> serMapId)
{
  int success = -1;
  if (serMapId.Count > 0 )
  {
    int count = RequestDL.DelServices(serMapId);
    if (count > 0)
    {
      success = count;
    }
  }
  return Json(new { success });
}

Jquery Ajax 脚本:

$.ajax({
  url: "/CRM/DeleteServices",
  type: "POST",
  data: postData,
  success: function (result) {
   alert(result.success);
   if (result.success > 0) {
     alert("Service(s) deleted successfully");
   }
   else {
     alert("Service(s) not deleted successfully");
   }
  },
  error: function () {
   alert("Something goes wrong at server side.");
  }
});

先感谢您。

4

3 回答 3

2

尝试更改对此的响应

return Json(new { success = success });

或者

return Json(new { success });

一些快速测试会产生以下结果:

//Returns 1
//this is not a valid JSON object
//If 'success' were a complex object, this would work as expected
return Json(success);

//Returns {"success":1}
return Json(new { success });

//Returns {"success":1}
return Json(new { success = success });
于 2013-05-07T07:26:36.050 回答
1

添加

数据类型:'json',

在 $.ajax 函数中

    $.ajax({
      url: "/CRM/DeleteServices",
      type: "POST",
      data: postData,
      dataType:'json',
    });
于 2013-05-07T07:03:40.563 回答
0

尝试以这种方式为 GET 请求返回成功对象:

return Json(success, JsonRequestBehavior.AllowGet);

以这种方式返回您的 Json 以进行 POST:

return Json(success);

不要忘记用 HttpPost 装饰你的方法,所以你的控制器应该看起来像这样

[HttpPost]
[Authorize]
public ActionResult DeleteServices(List<Int32> serMapId)
{
  int success = -1;
  if (serMapId.Count > 0 )
  {
    int count = RequestDL.DelServices(serMapId);
    if (count > 0)
    {
      success = count;
    }
  }
  return Json(success);
}

确保您的 Ajax 请求格式如下:

$.ajax({
  url: "/CRM/DeleteServices",
  type: "POST",
  data: postData,
  dataType: 'json',
  success: function (result) {
   alert(result.success);
   if (result.success > 0) {
     alert("Service(s) deleted successfully");
   }
   else {
     alert("Service(s) not deleted successfully");
   }
  },
  error: function () {
   alert("Something goes wrong at server side.");
  }
});
于 2013-05-07T06:36:14.090 回答