我正在 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 版本
1.确保
$(e.target).data('path')
包含价值。
2.将代码更改为:
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));
}
像下面一样尝试一下,
data: JSON.stringify({"path": $(e.target).data('path')}),
您好,您是否从 Ajax 方法中删除此行并尝试一下。 内容类型:“application/json;字符集=utf-8”,
.Net core 不接受ajax方法中的“contentType”字段。
将 JSON 数据发送到 ASP.NET Core 6 控制器操作需要进行一些更改。在这里,我创建了一个示例,其中包含所需的所有更改并测试通过 AJAX 发送的 JSON 数据
[HttpPost]
[Consumes("application/json")]
public IActionResult PostDataTest([FromBody] Employee[] employees)
{
return Json(employees);
}
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);
}
});
我创建了一个示例来处理这种情况,并将其发布在 GitHub 上 https://github.com/rajabb/MvcCore6JsonUploadSample 。我希望这能解决问题。