从后面的代码中的 ajax 请求中获取变量
Get variables from ajax request in code behind
所以,前段时间,我需要发出 ajax 请求来访问后面的代码。我做到了 ().
但现在我正在研究 asp.NET Core 2.0,它的工作方式有所不同。好吧,现在我可以提出请求了,但是由于某种原因变量为空(仅在后面的代码中,在客户端它们有内容。可能没什么大不了的,但我不明白为什么。
所以,这是我的 ajax 函数:
function Ajax(expression1, expression2, url, json, error) {
console.log(expression1+" - "+ expression2);
var request = { email: expression1, password: expression2 }
$.ajax({
url: url,
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
console.log(request);
if (expression1 === null || expression2===null)
window.location.href = resp[json];
else
document.getElementById(error).innerHTML = resp[json];
},
error: function (error) {
}
})
}
C# 代码:
public string ExternalLogin(string email, string name)
{
//TODO: Facebook login
// Redirect link example. Could be another one.
return "{\"facebook\":\"Home/About\"}";
}
ajax 函数发出请求并触发 c# 函数,returns 按我的要求执行。唯一的问题是空变量。为什么会这样?
编辑:用户 class 根据要求:
public class User
{
[JsonProperty(PropertyName ="email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "password")]
public string Password { get; set; }
}
参数绑定失败,因为您在这里发出 post 请求。
您必须将 [FromBody]
属性添加到参数中。
您可以在此处获取有关参数绑定的更多信息:
编辑:
您还传递了一个对象作为参数,因此您必须将路由参数更改为包含电子邮件和密码 属性 的对象,或者将您的 Content-Type 更改为 'application/x-www-form-urlencoded' 并传递一个查询字符串如 'email=....&password=....'
所以,前段时间,我需要发出 ajax 请求来访问后面的代码。我做到了 (
但现在我正在研究 asp.NET Core 2.0,它的工作方式有所不同。好吧,现在我可以提出请求了,但是由于某种原因变量为空(仅在后面的代码中,在客户端它们有内容。可能没什么大不了的,但我不明白为什么。
所以,这是我的 ajax 函数:
function Ajax(expression1, expression2, url, json, error) {
console.log(expression1+" - "+ expression2);
var request = { email: expression1, password: expression2 }
$.ajax({
url: url,
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
console.log(request);
if (expression1 === null || expression2===null)
window.location.href = resp[json];
else
document.getElementById(error).innerHTML = resp[json];
},
error: function (error) {
}
})
}
C# 代码:
public string ExternalLogin(string email, string name)
{
//TODO: Facebook login
// Redirect link example. Could be another one.
return "{\"facebook\":\"Home/About\"}";
}
ajax 函数发出请求并触发 c# 函数,returns 按我的要求执行。唯一的问题是空变量。为什么会这样?
编辑:用户 class 根据要求:
public class User
{
[JsonProperty(PropertyName ="email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "password")]
public string Password { get; set; }
}
参数绑定失败,因为您在这里发出 post 请求。
您必须将 [FromBody]
属性添加到参数中。
您可以在此处获取有关参数绑定的更多信息:
编辑:
您还传递了一个对象作为参数,因此您必须将路由参数更改为包含电子邮件和密码 属性 的对象,或者将您的 Content-Type 更改为 'application/x-www-form-urlencoded' 并传递一个查询字符串如 'email=....&password=....'