Abhishek Jain
Abhishek Jain

Reputation: 189

Ajax Post in Asp.net Core in .Net 6 is not working in Action method

I am making an ajax call in cshtml like below:

$(document).ready(function(){
    $('.dl-dir-list').click(function(e){
        console.log($(e.target).data('path'));
        console.log(JSON.stringify({path: $(e.target).data('path')}));
        $.ajax({
            type: "POST",
            url: '@Url.Action("GetFiles")',
            data: JSON.stringify({path: $(e.target).data('path')}),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                console.log(response);
            },
            error: function () {
                alert("Error while getting files");
            }
        });
    });
});

Action Method:

[HttpPost]
        public JsonResult GetFiles([FromBody]string path)
        {
            return Json(_fileService.GetFilesFromDirectory(path));
        }

Issue is always path parameter is null. What could be the issue? This is in Asp.Net COre, .Net 6 version

Upvotes: 2

Views: 8293

Answers (4)

Arokia Raj
Arokia Raj

Reputation: 1

Hi do you remove this line from the Ajax method and try it. contentType: "application/json; charset=utf-8",

.Net core not accept the "contentType" field in ajax method.

Upvotes: -1

Raja Brij Bhushan
Raja Brij Bhushan

Reputation: 21

There are some changes required to send JSON data to ASP.NET Core 6 Controller Action. Here I have created a sample with all changes required and test JSON data send via AJAX

  1. Your controller action should look like following
[HttpPost]
[Consumes("application/json")]
public IActionResult PostDataTest([FromBody] Employee[] employees)
{
    return Json(employees);
}

  1. Ajax method will look something like
var jsonData = [{"id":0,"name":"Very Long Employee Name with Many Characters 0","doj":"2022-08-21T11:23:24.1220131+05:30"},{"id":1,"name":"Very Long Employee Name with Many Characters 1","doj":"2022-08-20T11:23:24.1236139+05:30"},{"id":2,"name":"Very Long Employee Name with Many Characters 2","doj":"2022-08-19T11:23:24.1236164+05:30"},{"id":3,"name":"Very Long Employee Name with Many Characters 3","doj":"2022-08-18T11:23:24.1236167+05:30"},{"id":4,"name":"Very Long Employee Name with Many Characters 4","doj":"2022-08-17T11:23:24.123617+05:30"}];

var strJson = JSON.stringify(jsonData);

$.ajax({
        url: "/home/PostDataTest",
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: strJson,
        success: function (result) {
            $("#txtJsonReturned").val(result);
        },
        error: function (err) {
            $("#txtJsonReturned").val("Error while uploading data: \n\n" + err);
        }
    }); 

I have created a sample to handle this scenario and posted it on GitHub https://github.com/rajabb/MvcCore6JsonUploadSample . I hope that should solve the issue.

Upvotes: 0

Rena
Rena

Reputation: 36645

1.Be sure $(e.target).data('path') contains value.

2.Change your code to:

data: JSON.stringify($(e.target).data('path')),

The whole working demo:

View:

                                             //be sure add this `data-path` attribute
<input type="button" value="Create" class="dl-dir-list" data-path="aaa"/>

@section Scripts
{
    <script>
        $(document).ready(function(){
            $('.dl-dir-list').click(function(e){
                console.log($(e.target).data('path'))   //result: "aaa"
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("GetFiles")',
                    data: JSON.stringify($(e.target).data('path')), //change here....
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        console.log(response);
                    },
                    error: function () {
                        alert("Error while getting files");
                    }
                });
            });
        });
    </script>
}

Controller:

[HttpPost]
public JsonResult GetFiles([FromBody]string path)
{
    return Json(_fileService.GetFilesFromDirectory(path));
}

Upvotes: 4

TechGuy
TechGuy

Reputation: 4570

Try it like below,

 data: JSON.stringify({"path": $(e.target).data('path')}),

Upvotes: 0

Related Questions