aaarianme
aaarianme

Reputation: 292

AJAX post doesn't send data .Net Core

I have the below script. @username is a variable that comes from the model.

  <script>
                    var username = "@username"
                    $.ajax({

                          url: '@Url.Action("fetchChatsForUser")',
                          data: { Username: username },
                          type: "POST",
                          dataType: 'JSON',
                          contentType: "application/json",
                          success: function (e) {
                              console.log(e);
                              $("#Chatroom").html(e)
                          },
                          error: function (passParams) {
                              console.log("Error is " + passParams);
                          }
                      })

</script>

I checked the value of username and its not empty or null it's working. However in my controller when the fetchChatsForUser gets called by ajax, the data that's sent is null. here is the controller

public IActionResult fetchChatsForUser(string Username)
    {
        Chat Chats = new Chat();
        
        return PartialView("_Chatroom", Chats);
    }

The string Username in controller is always null even though im passing data in ajax. The method does get called though. What am I doing wrong here

Upvotes: 0

Views: 351

Answers (2)

Karney.
Karney.

Reputation: 5041

Because it is from body, so you can change like this.

Ajax, add JSON.stringify(username).

                var username = "@username"
                $.ajax({

                      url: '@Url.Action("fetchChatsForUser")',

                      data: JSON.stringify(username),
                      type: "POST",
                      dataType: 'JSON',
                      contentType: "application/json",
                      success: function (e) {
                          console.log(e);
                          //$("#Chatroom").html(e)
                      },
                      error: function (passParams) {
                          console.log("Error is " + passParams);
                      }
                  })

Bakend

    [HttpPost]
    public IActionResult fetchChatsForUser([FromBody]string Username)
    {
        Chat Chats = new Chat();

        return PartialView("_Chatroom", Chats);
        
    }

Result

enter image description here

Upvotes: 0

Asherguru
Asherguru

Reputation: 1741

Your ajax use POST and your function is Get. So you need to put [HttpPost]

[HttpPost]
public IActionResult fetchChatsForUser(string Username)

Or you try this jquery one.

<script>
var username = "@username";
$.post('@Url.Action("fetchChatsForUser")', { Username: username }).done(function (e) {
   console.log(e);
   $("#Chatroom").html(e);
});
</script>

Upvotes: 2

Related Questions