I have the following controller method:
[HttpPost]
public IActionResult AddNewMessage(string recipientUserId, string message)
{
var currentLoggedInUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
_chatMessageRepository.AddNewMessage(currentLoggedInUserId, recipientUserId, message);
return Ok();
}
And I am trying to send data to it, using the following JQuery code:
var data = {
recipientUserId: selectedUser,
message: message
};
$.ajax({
url: '/api/chatmessages',
type: 'POST',
data: data,
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
The result of this code, is that I get the request on my controller, but the parameters are always NULL
no matter what. Additionally, I tried to call the function JSON.Stringify()
upon the data, before sending them, but it did not do any difference. Keep in mind that I am devilishly trying to avoid to use a model class in this scenario, for project related reasons.
3
Answers
Make a class, lets say Message, which has properties recepientUserId and UserId and then replace the two parameters in your controller method with the Message class and add [FromBody] before it. With this u point out that the asp.net should try to map your data from the request’s body
Your controller method right now accepts the parameters from the url
The correct way to call it would be:
It is common for a post method to accept the payload in the body of the request, you can modify your controller method like this:
There is also a convention to put this attribute
[FromBody]
in your controller method like this: (It will also work without it)Since you are passing a Json type object, you can only use the object type to accept it in the background.
If you want to receive two string type parameters, there are generally two methods.
The first is as @David Edel said, you can pass values in querystring.
In the second method, you can pass values in data in Ajax, like the following:
Your Action: