1

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.

1
  • Is this a jQuery problem or one of .net? Please inspect the request to see whether it contains what it should contain
    – Nico Haase
    Commented Oct 9, 2024 at 10:09

2 Answers 2

1

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());
0

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 the method parameter class 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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.