2

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

0

4 Answers 4

4

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));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try it like below,

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

Comments

0

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.

1 Comment

@PeterJ did the same :). Thanks a lot for your suggestion.
-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.