I am making an ajax call in cshtml like below:
$(document).ready(function(){
$('.dl-dir-list').click(function(e){
console.log($(e.target).data('path'));
console.log(JSON.stringify({path: $(e.target).data('path')}));
$.ajax({
type: "POST",
url: '@Url.Action("GetFiles")',
data: JSON.stringify({path: $(e.target).data('path')}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function () {
alert("Error while getting files");
}
});
});
});
Action Method:
[HttpPost]
public JsonResult GetFiles([FromBody]string path)
{
return Json(_fileService.GetFilesFromDirectory(path));
}
Issue is always path parameter is null.
What could be the issue? This is in Asp.Net COre, .Net 6 version
3
Answers
Try it like below,
1.Be sure
$(e.target).data('path')
contains value.2.Change your code to:
The whole working demo:
View:
Controller:
There are some changes required to send JSON data to ASP.NET Core 6 Controller Action. Here I have created a sample with all changes required and test JSON data send via AJAX
I have created a sample to handle this scenario and posted it on GitHub https://github.com/rajabb/MvcCore6JsonUploadSample . I hope that should solve the issue.