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

Bou*_*ory 11 c# asp.net-mvc jquery

这是一个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);
         }
     });
Run Code Online (Sandbox Code Playgroud)

继承人我的行动:

    [HttpPost]
    public string LoadModelData(string id, string filename, string description)
    {
        return filename;
    }
Run Code Online (Sandbox Code Playgroud)

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

    'Oh No: test.pdf'. 
Run Code Online (Sandbox Code Playgroud)

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

Shy*_*yju 14

您期望(返回)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);
         }
     });
Run Code Online (Sandbox Code Playgroud)

datatype 属性告诉服务器客户端期望返回什么样的内容作为结果.

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


Dar*_*rov 8

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

data: "{'id': '"+docId +"', 'filename': '"+fileName+"', 'description': '"+fileDescription+"'}",
Run Code Online (Sandbox Code Playgroud)

绝对是可怕和错误的.你没有编码任何东西.只需一句报价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);
     }
 });
Run Code Online (Sandbox Code Playgroud)

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

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

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