Json没有得到实际的数据
本文关键字:数据 Json | 更新日期: 2023-09-27 18:12:20
我正在传递一些值给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 Script:
$.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.");
}
});
提前感谢。
尝试更改响应
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 });
添加
数据类型:json,
在美元。ajax函数
$.ajax({
url: "/CRM/DeleteServices",
type: "POST",
data: postData,
dataType:'json',
});
尝试以这种方式返回GET请求的成功对象:
return Json(success, JsonRequestBehavior.AllowGet);
POST返回Json:
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.");
}
});