I have a pretty basic ajax call with a json data object. The request gets to my controller but with out the data.
Ajax
$.ajax(
{
url: 'Playlist/AttachVideoToPlaylist',
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"RequestVerificationToken": tokenSet['requestToken']
},
type: "POST",
data: JSON.stringify({
"videoId": videoId,
"playlistId": listId
}),
success: function (data) {
console.log(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
That goes to this method, which for now is pretty basic
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> AttachVideoToPlaylist([FromBody] JObject data)
{
return new JsonResult(new { success = true });
}
the data
parameter is empty. I don’t know whether my data object in the ajax request is empty, but when I test
JSON.stringify({
"videoId": videoId,
"playlistId": listId
})
in a console.log()
it works fine.
What am I missing here? –> Solved.
Edits (Solution):
Rena’s answer fixed my issue. Adding the reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson
as a library and the addition to startup.cs
made it work.
2
Answers
Try this:
Fix ajax
Create VideViewModel class:
and fix your action:
If it is still doesn’t work , replace headers of your ajax with this:
That is because no matter you receive null or not null data in backend,it will always return a Json
success = true
.So it will be always get 200 Status code.What @Sergey did is a good workaround,but it may not resolve and explain your original problem for why
JObject
receives null value.The reason for
JObject
get null data,it may because you used asp.net core 3.x or 5.0.JObject
is used in Json.Net.And it has been removed from the ASP.NET Core shared framework since asp.net core 3.0.To meet your requirement,you could add Newtonsoft support:
1.Install the
Microsoft.AspNetCore.Mvc.NewtonsoftJson
package.2.Update
Startup.ConfigureServices
to callAddNewtonsoftJson
.Then what you could receive the data and get the ids like below:
Result: