question. I am having an issue when doing fetch post going to controller, fetch get is working fine, only the post the value is always null. But when I am using a postman it's working fine. Hope someone can help
//JS Side
var url = 'Test/SaveReportDetail';
var data = { username: 'example' };
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers: {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json;charset=UTF-8'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
//Controller Side
[HttpPost]
public JsonResult SaveReportDetail(string username)
{
//var RepObject = JsonConvert.DeserializeObject<ReportTemplate>(reportTemplate);
//return "t";
return Json("b");
}
You need to always use [FromBody]
for data from request body,besides above answer, if you only need to pass a string, you could pass the string directly instead of wrap in an object:
var url = 'Test/SaveReportDetail';
var username = 'example' ;
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(username),
headers: {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json;charset=UTF-8'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
Action:
[HttpPost]
public JsonResult SaveReportDetail([FromBody]string username)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With