I am trying to call an action in my controller with some JSON data, it seems to be reaching the action but the data is all null.
This is what my Ajax function looks like:
function AjaxPost(url, data) {
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
//I tried adding the following but to no avail:
processData: true,
traditional: true,
success: function (response) {
//success code
},
error: function (err) {
console.error(err);
}
});
}
This is how I make the AjaxPost function:
<a href="javascript:AjaxPost('./Chat/PrivateChat', {id:123, username:'username', connectionID:'connectionID'})">
This is the controller I am calling:
public IActionResult PrivateChat(int id, string username, string connectionID)
{
//at this point
//id = 0
//username = null
//connectionID = null
}
I have also tried methods from the following sources, but the data stays null:
2
Answers
Try adding
dataType: 'json'
. It will work. Thanks.!Well, based on your scenario and description, you would get null data always. Beause the way, you are sending Json data either you have to have Request model in controller wraping with [FromBody] or you should post data as query parameter like this way:
"http://localhost:5094/AjaxPostNull/PrivateChat2?id=" + data.id + "&username=" + data.username + "&connectionID=" + data.connectionID
Let’s have a look at practice, how we could achieve that:
Way: FormBody Wrapper:
Request Model:
Controller Signature:
Note: If you send request along with json model, you should wrap the controller with [FromBody]
Script:
Output:
Alternative way: Query String
Output:
Note: Please refer to this official document if you want to know more.