I am trying to pass a string to an IActionResult
function in an asp.net core 3.1 controller.
Ajax:
$(function () {
$('#ddlUsers').change(function () {
$.ajax({
url: '@Url.Action("GetUserInfoPartial", "UserInfo")',
method: 'POST',
data: { userId: 'test' },
contentType: 'application/json',
dataType: 'html'
}).done(function (r) {
$('#partialID').html(r);
});
});
});
C#:
[HttpPost]
public IActionResult GetUserInfoPartial(string userId)
{
return PartialView("_UserPartial", userId);
}
Breakpoints in GetUserInfoPartial
are hit, but userId is always null.
What am I missing?
2
Answers
you can try to remove ‘application/json’, but it is sometimes tricky, depends on net version
If you are not lucky there are another 2 ways
easy way – to use Get instead of Post
action
and harder one, if you want to use ‘application/json’ content type
Create ViewModel
ajax
action
you can remove ‘application/json’, and dataType: ‘html’ then it will work properly.
$.ajax({
url: ‘@Url.Action("GetUserInfoPartial", "UserInfo")’,
method: ‘POST’,
data: { userId: ‘test’ },
success: function (r) {
$(‘#partialID’).html(r);
});