Reputation: 180
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");
}
Upvotes: 4
Views: 6726
Reputation: 20116
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)
Upvotes: 4
Reputation: 964
I recommend you to use your actions like that. Try this. It will work.
[HttpPost("SaveReportDetail")]
public JsonResult SaveReportDetail([FromBody]SaveReportDetailInput input)
{
var userName = input.Username;
return Json("b");
}
Input Class example
public class SaveReportDetailInput {
public string Username { get; set; }
}
Upvotes: 2