我正在嘗試將值串列從視圖發送到控制器。我從網上嘗試了很多解決方案,但都沒有成功。
我的 View HTML Table 資料串列通過 JSON 發送到控制器,但即使我使用該串列也是空的 JSON.stringify
這是我的代碼
JavaScript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var customers = new Array();
$("#tblCustomers TBODY TR").each(function () {
var row = $(this);
var customer = {};
//skill.skill_name = row.find("TD").eq(0).html();
customer.CNIC = row.find("TD").eq(1).html();
customers.push(customer);
});
console.log(customers);
console.log(JSON.stringify(customers));
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
//traditional: true,
url: "/Admin/Reconcile/Customers",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(customers),
dataType: "json",
success: function (r) {
alert(r " record(s) inserted.");
location.reload();
}
});
});
</script>
控制器動作:
public JsonResult Customers(List<String> customers)
{
}
uj5u.com熱心網友回復:
首先,您需要創建一個這樣的模型:
public class Customer {
public string CNIC { get; set; }
}
然后因為你在ajax中傳遞json型別的資料,你需要[FromBody]在行動中使用:
public JsonResult Customers([FromBody]List<Customer> customers)
{
}
uj5u.com熱心網友回復:
您正在發送一組物件,因此要使模型系結器正常作業,您應該接受 SomeModel 串列,其中 SomeModel 應具有屬性 CNIC。檢查此處的檔案https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api關于如何系結物件.
所以你要發送這個:
[
{
"CNIC":"somevalue",
"CNIC":"somevalue"
}
]
而你正試圖將它系結到一個字串串列,它不會發生。嘗試將其與 SomeModel 串列系結:
public class SomeModel
{
public string CNIC { get; set; }
}
還可以[IgnoreAntiforgeryToken]在您的操作上方嘗試此屬性。如果它有效,那么您應該在 post 請求中發送防偽令牌。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403361.html
標籤:
上一篇:合并具有重復鍵的json陣列
