skip to Main Content

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

3

Answers


  1. Try it like below,

     data: JSON.stringify({"path": $(e.target).data('path')}),
    
    Login or Signup to reply.
  2. 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));
    }
    
    Login or Signup to reply.
  3. 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: nn" + 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search