I post data using fetch like this in my client js scripts
fetch('/myarea/mycontroller/myaction', {
method: 'post',
body: JSON.stringify({ name: namevalue, address: addressvalue })
})
.then(function (response) {
if (response.status !== 200) {
console.log('fetch returned not ok' + response.status);
}
response.json().then(function (data) {
console.log('fetch returned ok');
console.log(data);
});
})
.catch(function (err) {
console.log(`error: ${err}`);
});
}, false);
Then on my controller
[HttpPost]
public async Task<IActionResult> MyAction(string name, string address)
{
// Error, name and address is null here, shouldn't be!
// more code here ...
}
My controller action is being called correctly, and I am able to debug inside it, but no data being passed. What could be wrong here? Thanks
The controller action is expecting query parameters (/myaction?name=myname&address=myaddress
). That's the default.
You're sending them in the body.
You can change the javascript to send them as query parameters. (see here: https://github.com/github/fetch/issues/256)
Or you can tell the controller action to take the values from the body:
[HttpPost]
public async Task<IActionResult> MyAction([FromBody] Person person)
{
var myName = person.Name;
}
public class Person
{
public string Name {get; set; }
public string Address {get; set; }
}
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