Ajax Post in Asp.net Core in .Net 6 在 Action 方法中不工作

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

我正在 cshtml 中进行 ajax 调用,如下所示:

$(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");
            }
        });
    });
});

操作方法:

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

问题始终是路径参数为空。 可能是什么问题?这是 Asp.Net COre,.Net 6 版本

像下面这样尝试,

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

1.Be 确定 $(e.target).data('path') 包含值。

2.Change 您的代码:

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

整个工作演示:

查看:

                                             //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>
}

控制器:

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