Search code examples
c#jqueryajaxasp.net-coreasp.net-core-mvc

.NET Core Ajax Call to Controller


This is my Index.cshtml:

@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <h1 class="display-4">Welcome to SyncFusion</h1>
    <input type="text" name="username" id="username" value=''>
    <button type="button" id="btnMe">Click me!</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>   
   $(document).ready(function () {
   $("#btnMe").click(function () {
       $.ajax({
          type: "POST",
          url: "HOME/Users",
          data: JSON.stringify({ username: $("#username").val() }),
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (response) {
            $(response).each(function (index, item) {
               console.log(item);
            });
          }
      });
   });
});
</script>

This is my HomeController. I have passed string username just for testing purpose and I'm getting null value:

public JsonResult Users(string username){
    List<User> Users = new List<User>()
    {
        new User { Id = 1, Name = "John Doe", Age = 30 },
        new User { Id = 2, Name = "Jane Doe", Age = 25 },
        new User { Id = 3, Name = "Sammy Doe", Age = 22 }   
    };
    return Json(Users);
}

This is my Model User.cs:

public class User
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public int Age { get; set; }
}

I tried without using JSON.stringify, but still shows null value. Am I missing something here? Any help would greatly appreciated.


Solution

  • Change the contentType to:

    $(document).ready(function () {
        $("#btnMe").click(function () {
            $.ajax({
               type: "POST",
               url: "/HOME/Users",
              
               data: { username: $("#username").val() },
               contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    
               dataType: "json",
               success: function (response) {
                 $(response).each(function (index, item) {
                    console.log(item);
                 });
               }
           });
        });
    });
    

    Actually this is the default value. Therefore, you can omit this parameter from the .ajax() call.

    For more information the contentType description: https://api.jquery.com/jQuery.ajax/

    BTW, if you want to keep using the Pascal naming conventions in the view script possible to add one more parameter (serialization settings) when returning the result:

    return Json(Users, new System.Text.Json.JsonSerializerOptions());