我是 JS 的新手,对 AJAX 的经验更少。我只是想将一个值传递给后面的代码并返回一个扩展的响应。 问题是,尽管调用成功,但从 AJAX 传递到 C# 的字符串值永远是“未定义”以外的任何值,这让我发疯。
JS
function test() {
var message = "this is a test" ;
Display(message);}
function Display(words) {
var hummus = { 'pass': words};
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: hummus,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words + "\n\nError: " + lion);
}
});}
背后的代码
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
string beans = pass + ". We repeat this is only a test.";
return beans;
}
最终结果总是“你的财富:未定义。我们重复一遍,这只是一个测试。” 我只想知道我错过了什么。 是的,这可能是一个愚蠢的问题,但我的搜索结果没有任何帮助。
最佳答案
您的问题是您试图在您的方法 public static string ShowMe(string pass)
中接受一个字符串,但您传递的是一个 JavaScript 对象作为您的数据。查看何时进行 Ajax 调用 ASP.Net 将尽最大努力将您发布的数据与参数中的类型相匹配 - 称为模型绑定(bind)。当这无法实现时,您会收到一个空值。
因此在您的 JavaScript 中,您使用以下方法传递一个 JavaScript 对象:
var hummus = { 'pass': words};
$.ajax({
....,
....,
data: hummus,
如果你想发布一个对象,那么你的 Controller /方法需要有一个你的 JS 将绑定(bind)到的 C# 模型(类)。
所以改变你的方法来接受一个模型:
// somewhere in your code put this little model
// this is what your JavaScript object will get bound to when you post
public MyModel{
// this is to match the property name on your JavaScript object, its case sensitive i.e { 'pass': words};
public string pass {get;set;}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(MyModel model)
{
// you can now access the properties on your MyModel like this
string beans = model.pass + ". We repeat this is only a test.";
return beans;
}
关于c# - 将字符串从 AJAX 传递到后面的 ASP.NET C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004518/