我在 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 版本中
uj5u.com熱心網友回復:
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));
}
uj5u.com熱心網友回復:
像下面這樣試試,
data: JSON.stringify({"path": $(e.target).data('path')}),
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461531.html
標籤:jQuery 阿贾克斯 asp.net-mvc asp.net 核心 .net-6.0
下一篇:如何使用Ajax傳遞多個引數
