skip to Main Content

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 Home Controller
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.

2

Answers


  1. Change the contentType to:

    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    

    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());
    
    Login or Signup to reply.
  2. Since you are pass a json object to the backend, and the object name is username, so you should modify the public JsonResult Users(string username) to the [HttpPost] public JsonResult Users([FromBody] UserRequest request) and details codes as below:

    public class UserRequest
    {
        public string Username { get; set; }
    }
    

    If you don’t want to modify the parameter , you should modify your ajax to use this data: { username: $("#username").val() }. and modify details like below:

    <script>
    
           $(document).ready(function () {
           $("#btnMe").click(function () {
               $.ajax({
                  type: "POST",
                  url: "HOME/Users",
                    data: { username: $("#username").val() }, // Send data as a form-urlencoded parameter
    
                    success: function (response) {
                    $(response).each(function (index, item) {
                       console.log(item);
                    });
                  }
              });
           });
        });
    </script>
    

    Result:

    enter image description here

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