问题描述
这是MVC3应用.我通过以下JavaScript调用了我的操作:
This is an MVC3 app. I have the following javascript call to my action:
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);
}
});
这里是我的动作:
[HttpPost]
public string LoadModelData(string id, string filename, string description)
{
return filename;
}
我运行代码,用参数调用该动作,没有什么为空,但是每次都调用错误函数.因此,每次都会出现带有"Oh no"(否)的警报框,但是从操作返回的字符串是正确的.如果文件名是test.pdf,错误警告框将显示
I run the code, the action gets called with the parameters, nothing is null, but the error function gets called every time. So the alert box with 'Oh no' in it appears every time, but the string being returned from the action is correct. If the filename is test.pdf the error alert box says
'Oh No: test.pdf'.
我查看了Firebug,没有任何错误.尽管没有错误,为什么没有调用成功函数?
I looked in Firebug and there are no errors. Why isn't the success function being called despite the fact there are no errors?
推荐答案
您期望(返回)操作方法中的string
值.为什么需要将数据类型指定为json
呢?删除它,看看会发生什么.而且响应中没有 d 属性!因此只需在警报中使用结果.
You are expecting (returning) a string
value from your action method. Why do you need to specify the datatype as json
then ? Remove that and see what happens. And there is no d property from the response ! so just use result in the alert.
$.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
属性告诉服务器客户端期望返回什么样的内容.
the datatype
property tells the server that what kind of content the client is expecting back as the result.
如达林所说,请使用JSON.stringify
方法构建JSON请求.更新此答案,为将来的访问者提供正确的方法.
EDIT : As Darin mentioned, Please Use the JSON.stringify
method to build the JSON request. Updating this answer to include correct way for future visitors.
这篇关于没有一个JQuery对MVC操作的ajax调用总是返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!