[英]fetch post method with razor page doesn't send body
我想使用 ajax(获取 api)帖子将页面中的一些数据传输到页面 model。 我设法进入“OnPostTest”处理程序,但我没有收到任何数据 - 变量“json”是 null。 我的问题在哪里? 是在我的 ajax 调用还是在 razor 页面 model 方法中? 谢谢
razor 页页 model
public JsonResult OnPostTest(string json)
{
return new JsonResult(json);
}
js
async function getData() {
fetch('./test/Test',
{
method: "POST",
body: JSON.stringify({
json: 'yourValue'
}),
headers: {
'X-CSRF-TOKEN': document.getElementsByName("__RequestVerificationToken")[0].value,
'Content-Type': 'application/json',
Accept: 'application/json',
}
})
.then(function (res) { return res.json(); })
.then(function (data) { alert((data)) })
}
razor页面
<form method="post">
<button type="button" onclick="getData(this)" value="1">send</button>
</form>
----编辑---- js
async function getData() {
fetch('./test/Test',
{
method: "POST",
body: JSON.stringify(
{
name: "myname",
value: 1,
date:new Date()
}
),
headers: {
'X-CSRF-TOKEN': document.getElementsByName("__RequestVerificationToken")[0].value,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
.then(function (res) { return res.json(); })
.then(function (data) { alert((data)) })
}
razor 页面 - 页面型号
public JsonResult OnPostTest([FromBody] ViewModel json)
{
return new JsonResult(json.Name);
}
public class ViewModel
{
public string Name { get; set; }
public int Value { get; set; }
public DateTime date { get; set; }
}
headers
需要更改。 因为bakend接收的是一个字符串,所以body应该只是一个字符串。
fetch('[url]',
{
method: "POST",
body: JSON.stringify(
'yourValue'
),
headers: {
RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
'Content-Type': 'application/json',
Accept: 'application/json',
}
})
.then(function (res) { return res.json(); })
.then(function (data) { console.log(data) })
在页面处理程序中添加[FromBody]
。
public JsonResult OnPostTest([FromBody]string json)
{
return new JsonResult(json);
}
编辑:
如果传递复杂的 object {name:"myname",value:"5"}
,则需要使用JSON.stringify()
对 object 进行序列化。
body: JSON.stringify(
name:"myname",
value:"5"
),
并且bakend应该使用一个复杂的object来接收。
public JsonResult OnPostTest([FromBody]ViewModel json)
{
return new JsonResult(json);
}
public class ViewModel
{
public string Name { get; set; }
public int Value { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.