Aps.net 核心 Razor 页面 [FromBody] Ajax post 模型始终为空
Aps.net core Razor page [FromBody] Ajax post Model always is null
在 Asp.Net 核心中,我有一个剃刀页面,我想将 Ajax post 发送到 Post 方法,但我总是得到 null model.here 是我的简化问题。
public class IndexModel : PageModel
{
public void OnPost([FromBody]A A)
{
if (ModelState.IsValid)
{
}
}
}
这是我的模型:
[JsonObject(MemberSerialization.OptOut)]
public class A
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string CityId { get; set; }
[JsonProperty]
public string Infected { get; set; }
[JsonProperty]
public string Susceptible { get; set; }
[JsonProperty]
public string Recovered { get; set; }
[JsonProperty]
public string CityName { get; set; }
}
这是我的 Ajax 请求:
function f(event) {
var token = $("input[name='__RequestVerificationToken']").val();
var c = {};
c["Id"] = "1";
c["CityId"] = "2";
c["Infected"] = "3";
c["Susceptible"] = "4";
c["Recovered"] = "5";
c["CityName"]=""
$.ajax({
url: "./DynamicEpidemic",
type: "post",
contentType: 'application/json; charset=utf-8',
headers:
{
"RequestVerificationToken": token
},
data: { A: JSON.stringify(c)},
success: function () {
alert("OK");
}
});
console.log(JSON.stringify(c));
}
发送的json对象是这样的:
{"Id":"1","CityId":"2","Infected":"3","Susceptible":"4","Recovered":"5","CityName":""}
但我的模型总是 null.ModelState 错误是
Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
尝试更改为 data: JSON.stringify(c)
。
在 Asp.Net 核心中,我有一个剃刀页面,我想将 Ajax post 发送到 Post 方法,但我总是得到 null model.here 是我的简化问题。
public class IndexModel : PageModel
{
public void OnPost([FromBody]A A)
{
if (ModelState.IsValid)
{
}
}
}
这是我的模型:
[JsonObject(MemberSerialization.OptOut)]
public class A
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string CityId { get; set; }
[JsonProperty]
public string Infected { get; set; }
[JsonProperty]
public string Susceptible { get; set; }
[JsonProperty]
public string Recovered { get; set; }
[JsonProperty]
public string CityName { get; set; }
}
这是我的 Ajax 请求:
function f(event) {
var token = $("input[name='__RequestVerificationToken']").val();
var c = {};
c["Id"] = "1";
c["CityId"] = "2";
c["Infected"] = "3";
c["Susceptible"] = "4";
c["Recovered"] = "5";
c["CityName"]=""
$.ajax({
url: "./DynamicEpidemic",
type: "post",
contentType: 'application/json; charset=utf-8',
headers:
{
"RequestVerificationToken": token
},
data: { A: JSON.stringify(c)},
success: function () {
alert("OK");
}
});
console.log(JSON.stringify(c));
}
发送的json对象是这样的:
{"Id":"1","CityId":"2","Infected":"3","Susceptible":"4","Recovered":"5","CityName":""}
但我的模型总是 null.ModelState 错误是
Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
尝试更改为 data: JSON.stringify(c)
。