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?
CodePudding user response:
you can try to remove 'application/json', but it is sometimes tricky, depends on net version
$.ajax({
url: '@Url.Action("GetUserInfoPartial", "UserInfo")',
method: 'POST',
data: { userId: 'test' },
success: function (r) {
$('#partialID').html(r);
});
If you are not lucky there are another 2 ways
easy way - to use Get instead of Post
$.ajax({
url: '@Url.Action("GetUserInfoPartial", "UserInfo")' 'test',
method: 'GET',
success: function (r) {
$('#partialID').html(r);
});
action
[HttpGet("{userId}")]
public IActionResult GetUserInfoPartial(string userId)
and harder one, if you want to use 'application/json' content type
Create ViewModel
public class ViewModel
{
public string UserId {get; set;}
}
ajax
$.ajax({
url: '@Url.Action("GetUserInfoPartial", "UserInfo")',
method: 'POST',
data: JSON.stringify( { userId: 'test' }),
contentType: 'application/json',
success: function (r) {
$('#partialID').html(r);
});
action
[HttpPost]
public IActionResult GetUserInfoPartial([FromBody] ViewModel model)
{
return PartialView("_UserPartial", model.UserId);
}
