skip to Main Content

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


  1. 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);
    }   
    
    Login or Signup to reply.
  2. 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);
    });

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search