我将一些值传递给MVC Controller并返回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.");
}
});
提前谢谢。
答案 0 :(得分: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 });
答案 1 :(得分:1)
添加
数据类型: 'JSON',
$ .ajax函数中的
$.ajax({
url: "/CRM/DeleteServices",
type: "POST",
data: postData,
dataType:'json',
});
答案 2 :(得分: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.");
}
});