如何将一个简单的Javascript数组绑定到MVC3控制器操作方法



以下是我用来创建数组并发送它的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");
}

如果要将JSON发送到服务器,则需要JSON。对数据进行字符串化,并将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数据填充服务器端模型。你可以在这里阅读更多关于模型活页夹的信息。

最新更新