ChasetopherB
ChasetopherB

Reputation: 464

Ajax call doesn't pass string to controller

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?

Upvotes: 0

Views: 853

Answers (2)

Maryam Yavarifard
Maryam Yavarifard

Reputation: 32

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); });

Upvotes: 0

Serge
Serge

Reputation: 43880

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);
}   

Upvotes: 1

Related Questions