Lavlesh Jaiswal
Lavlesh Jaiswal

Reputation: 11

How to use Ajax in Visual Studio 2022 / ASP.NET Core 5.0 MVC?

I'm try to call action method of controller using Ajax but, we are getting null in parameter.

This is my code:

function Load() {
        $.ajax({
            type: "POST",
            url: "/Attendence/GetData",
            dataType: "json",
            data:  "{'name':'lavlesh'}",
             contentType:'application/json; charset=utf-8',
            success: function(res) {
                alert(res)
            },
            error: function(res) {
                alert(res.d)
            }
        });
}

Same code working in Visual Studio 2019 and ASP.NET Core MVC, but in VS 2022 and ASP.NET Core 5.0 MVC, I'm getting null.

Please help me resolve this issue.

Thanks

Upvotes: 1

Views: 886

Answers (1)

Md Farid Uddin Kiron
Md Farid Uddin Kiron

Reputation: 22457

Same code working in Visual Studio 2019 and ASP.NET Core MVC, but in VS 2022 and ASP.NET Core 5.0 MVC, I'm getting null.

I have successfully reproduce your issue as you have a look:

enter image description here

Here, the way you are passing data is incorrect, data: "{'name':'lavlesh'}". Becase you already define that as dataType: "json" nop need to pass it again in json format. You can achieve in following way:

data: { name: "lavlesh"
      },

In addition, when you define dataType: "json" so no longer you need to specify contentType:'application/json; charset=utf-8' in this case your data will twice converted and you will lose data while posting.

Note: Point that here: name key must be same format as your controller parameter as GetData(string name)

Complete Demo:

Let's consider you have a Controller as following:

        [HttpPost]
        public IActionResult GetData(string name)
        {
           return Ok(name);
        }

So we can call that Controller as following way::

@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            alert("Okay");
            $.ajax({
                type: "POST",
                url: "http://localhost:5094/Attendence/GetData",
                dataType: "json",
                data: {name: "lavlesh"},
                success: function (res) {
                    alert(res)
                },
                error: function (res) {
                    alert(res.d)
                }
            });
           

        });
    </script>
}

Final Output:

enter image description here

Upvotes: 1

Related Questions