2

这是我用来创建数组并以它的方式发送它的 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对象是用我需要的值正确构造的。

我的对象必须在控制器的后端使用什么数据类型?

我试过了,但变量仍然为空且未绑定。

[Authorize]
[HttpPost]
public ActionResult UpdateCart(object[] items) // items remains null.
{

    // Some magic here.
    return RedirectToAction("Index");
}
4

1 回答 1

10

如果要将 JSON 发送到服务器,则需要JSON.stringify数据并指定 contentTypeapplication/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 数据填充您的服务器端模型。您可以在此处阅读有关模型绑定器的更多信息。

于 2012-04-06T16:36:11.553 回答