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

Time:04-22

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

CodePudding user response:

Try it like below,

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

CodePudding user response:

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"  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));
}
  • Related