[{prodId:'10',qnty:'12',total:'1200'},
{prodId:'11',qnty:'2',total:'10'},
{prodId:'4',qnty:'10',total:'50'}]
我有以下类(class)
public class ListItem{
public int prodID {get;set;}
public int qnty {get;set;}
public decimal total {get;set;}
}
上面的 json 数组将从 ajax 调用发送到 action 方法。在操作方法中,我需要构建一个 List<ListItem>
从 json 数组中收集。我该怎么做?
更新 这是 Controller
public class ShoppingCartController : Controller
{
public JsonResult AddToShoppingCart(string jsonString)
{
int carId = 0;
string[] str= jsonString.Split(',');
for (int i = 0; i < str.Length; i++)
{
if (str[i] == "cartId")
{
string tmp = str[i].Split(':').LastOrDefault();
carId = int.Parse(tmp);
if (carId == -1)
{
//create new cart
}
else {
}
}
}
}
这是ajax:
$('#addToCartForm #add').on('click', function () {
$.ajax({
url: 'ShoppingCart/AddToShoppingCart',
method: 'post',
data: JSON.stringify(item),
dataType: 'json',
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
最佳答案
将您的 POST 方法更改为
public JsonResult AddToShoppingCart(List<ListItem> model)
和脚本
$('#addToCartForm #add').on('click', function () {
$.ajax({
url: '@Url.Action("AddToShoppingCart", "ShoppingCart")', // don't hard code
method: 'post',
data: JSON.stringify({ 'model': item }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
假设 item
是您显示的 javascript 数组。 DefaultModelBinder
将正确绑定(bind)集合
关于c# - 如何从 json 数组创建列表集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34378490/