Net Core Ajax Jquery Passing Null Value to Controller, Vs2022, .Net 6

Viewed 152

I tried Different forms of calls, same names, with stringify, without stringify.... but nothing works.

my html

<input type="text" id="txtName"/>
<input type="button" id="btnGet" value="Get Current Time"/>
<input type="text" id="txtresponse"/>

my jscript

$(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: '{name: "' + $("#txtName").val() + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        //alert(response);
                        $("#txtresponse").val(response);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        //alert(response.responseText);
                    }
                });
            });
        }); 
    

my controller

[HttpPost]
public ContentResult AjaxMethod(string name)
{
    string currentDateTime = string.Format("Hello {0}.\nCurrent DateTime: {1}", 
                                                      name, DateTime.Now.ToString());
    return Content(currentDateTime);
}

Here, the "AjaxMethod" controller always receives null as the value of the "name" parameter.

My Version is .Net 2022 and .Net 6

Thank you very much for your help

3 Answers

You don't need to concatenate a string to send data to the controller using AJAX. You can simply give it a javascript object to send. Try the following:

$(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: {
                        name: $("#txtName").val() 
                    },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        //alert(response);
                        $("#txtresponse").val(response);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        //alert(response.responseText);
                    }
                });
            });
        }); 

you can create model class

public class NameModel
{
  public string Name {get; set;}
}

fix ajax data

 data: JSON.stringify({ name:$("#txtName").val() }),

and add frombody attribute to the action

public ContentResult AjaxMethod([FromBody]NameModel model)
{
  var name=model.Name;
  ... another your code
}

or leave action as it is but remove "application/json; charset=utf-8" contentType from ajax

 $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: {name:  $("#txtName").val() },
                    ....

ASP.NET 6 MVC receives the application/x-www-form-urlencoded type data by default if you do not specify(e.g use [FromBody]/[FromQuery]) the source.

Change your code like below:

$(function () {
    $("#btnGet").click(function () {
        $.ajax({
            type: "POST",
            url: "/Home/AjaxMethod",
            data: { name: $("#txtName").val() },      //change here....
  //contentType: "application/json; charset=utf-8",   //remove it
                                                      // default is application/x-www-form-urlencoded
            dataType: "json",
            success: function (response) {
                //alert(response);
                $("#txtresponse").val(response);
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                //alert(response.responseText);
            }
        });
    });
}); 
Related