這是我的 ajax 代碼
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = JSON.stringify(sRow, ["ID"]);
var view = {
CompanyCode: $('#Company').val(),
RolesCode: $('#Roles').val(),
ID,
};
$.ajax({
method: "POST",
url: '@Url.Action("Save")',
data: $('#formData').serialize(),
success: function (data) {
alert(data '!!!')
},
error: function () {
alert('ERROR')
}
})
})
這是我的控制器
[HttpPost]
public IActionResult Save(RightsModel view)
{
return View();
}
這是我的模型
public class RightsModel
{
public List<string> ID { get; set; }
public string Company { get; set; }
public string Roles { get; set; }
}
這是我的觀點
<form id="formData">
@Html.DropDownListFor(m => m.Company, Model.Company)
@Html.DropDownListFor(m => m.Roles, Model.Roles)
<button id="RolesSave" class="btn btn-primary btn-light" type="submit">存檔</button>
<table id="table"></table>
我的問題是當我使用代碼 $('#formData').serialize() 時。它可以正常將View中的資料轉換為Model。但是當我使用 JSON.serialize(view) 時,它無法達到相同的目標。即使我將[FormBody]添加到Action中,也無法獲取任何相關資訊。有什么建議?
uj5u.com熱心網友回復:
JSON.serialize在js中不存在,我們通常使用JSON.stringify.并且你需要確保view的模型結構與model相同RightsModel。并且你需要添加contentType:"application/json",到ajax中,因為你想將json型別的資料傳遞給action。這里是一個演示:
js:
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = [];
sRow.forEach(function (item, index) {
ID.push("" item.ID);
});
var view = {
Company: $('#Company').val(),
Roles: $('#Roles').val(),
ID: ID
};
$.ajax({
method: "POST",
url: '@Url.Action("Save")',
data: JSON.stringify(view),
contentType:"application/json",
success: function (data) {
alert(data '!!!')
},
error: function () {
alert('ERROR')
}
})
})
行動:
[HttpPost]
public IActionResult Save([FromBody]RightsModel view)
{
return View();
}
結果:

我試著用你var ID = ["1", "2", "3"];來測驗,它可以作業。ID需要輸入List<string>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314696.html
標籤:阿贾克斯 asp.net核心 asp.net-core-mvc
下一篇:選擇器似乎沒有回傳的選項
