这是我用来创建数组并在其上发送它的javascript代码:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#update-cart-btn").click(function() {
var items = [];
$(".item").each(function () {
var productKey = $(this).find("input[name='item.ProductId']").val();
var productQuantity = $(this).find("input[type='text']").val();
items[productKey] = productQuantity;
});
$.ajax({
type: "POST",
url: "@Url.Action("UpdateCart", "Cart")",
data: items,
success: function () {
alert("Successfully updated your cart!");
}
});
});
});
</script>
使用我需要的值正确构造items
对象。
我的对象必须在控制器的后端使用哪种数据类型?
我尝试了这个但是变量仍然是null并且没有绑定。
[Authorize]
[HttpPost]
public ActionResult UpdateCart(object[] items) // items remains null.
{
// Some magic here.
return RedirectToAction("Index");
}
答案 0 :(得分:10)
如果要将JSON发送到服务器,则需要JSON.stringify数据,并将contentType指定为application/json
,以便与MVC3模型绑定器配合使用:
$.ajax({
type: "POST",
url: "@Url.Action("UpdateCart", "Cart")",
data: JSON.stringify(items),
success: function () {
alert("Successfully updated your cart!");
},
contentType: 'application/json'
});
作为服务器上的数据类型,您可以使用强类型类,例如:
public class Product
{
public int ProductKey { get; set; }
public int ProductQuantity { get; set; }
}
[HttpPost]
public ActionResult UpdateCart(Product[] items)
{
// Some magic here.
return RedirectToAction("Index");
}
但是你需要稍微调整items
列表:
var items = [];
$(".item").each(function () {
var productKey = $(this).find("input[name='item.ProductId']").val();
var productQuantity = $(this).find("input[type='text']").val();
items.push({ "ProductKey": productKey, "ProductQuantity": productQuantity });
});
基本上,JSON对象结构应该与C#模型类结构匹配(属性名称也应该匹配),然后MVC中的模型绑定器会使用您发送的JSON数据填充服务器端模型。您可以阅读有关模型绑定器here的更多信息。