JQuery ajax调用MVC操作总是在没有错误时返回错误

这是一个MVC3应用程序。 我有以下javascript调用我的操作:

function editDescription(docId,fileName, fileDescription) { $.ajax({ type: "POST", url: "/OrderDetail/LoadModelData", contentType: "application/json; charset=utf-8", data: "{'id': '"+docId +"', 'filename': '"+fileName+"', 'description': '"+fileDescription+"'}", dataType: "json", success: function (result) { alert("ok: "+ result.d); }, error: function (result) { alert('Oh no: '+ result.responseText); } }); 

inheritance人我的行动:

  [HttpPost] public string LoadModelData(string id, string filename, string description) { return filename; } 

我运行代码,使用参数调用操作,没有任何内容为null,但每次调用错误函数。 因此,每次都会出现带有“Oh no”的警告框,但是从动作返回的字符串是正确的。 如果文件名是test.pdf,则错误警告框显示

  'Oh No: test.pdf'. 

我看着Firebug并没有错误。 尽管没有错误,为什么不调用成功函数?

您期望(返回)您的操作方法中的string值。 为什么需要将数据类型指定为json呢? 删除它,看看会发生什么。 响应中没有d属性! 所以只需在警报中使用结果。

 $.ajax({ type: "POST", url: "/OrderDetail/LoadModelData", contentType:"application/json; charset=utf-8", data: JSON.stringify({ id: docId, filename: fileName, description: fileDescription }), success: function (result) { alert("ok: "+ result); }, error: function (result) { alert('Oh no: '+ result.responseText); } }); 

datatype属性告诉服务器客户端期望返回哪种内容作为结果。

编辑:正如Darin所提到的,请使用JSON.stringify方法来构建JSON请求。 更新此答案以包含未来访问者的正确方法。

永远不要使用字符串操作构建JSON:

 data: "{'id': '"+docId +"', 'filename': '"+fileName+"', 'description': '"+fileDescription+"'}", 

绝对是可怕和错误的 。 你没有编码任何东西。 在description只需引用一句话,一切都会破裂。 在操作JSON时始终使用JSON解析器

像这样:

 $.ajax({ type: "POST", url: "/OrderDetail/LoadModelData", contentType: "application/json; charset=utf-8", data: JSON.stringify({ id: docId, filename: fileName, description: fileDescription }), success: function (result) { alert("ok: "+ result.filename); }, error: function (result) { alert('Oh no: '+ result.responseText); } }); 

JSON.stringify方法是本机内置的现代浏览器。 如果您需要支持旧版浏览器,可以包含json2.js脚本

另一个错误是你的控制器动作签名。 在ASP.NET MVC控制器中,操作必须返回ActionResults,而不是字符串:

 [HttpPost] public ActionResult LoadModelData(string id, string filename, string description) { return Json(new { filename = filename }); }