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

Onl*_*ere 2 javascript modelbinders asp.net-mvc-3

这是我用来创建数组并在其上发送它的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>
Run Code Online (Sandbox Code Playgroud)

使用items我需要的值正确构造对象.

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

我尝试了这个,但变量保持为null并且没有绑定.

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

    // Some magic here.
    return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 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'
        });
Run Code Online (Sandbox Code Playgroud)

作为服务器上的数据类型,您可以使用强类型类,例如:

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");
}
Run Code Online (Sandbox Code Playgroud)

但是你需要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 });
});
Run Code Online (Sandbox Code Playgroud)

基本上JSON对象结构应该与C#模型类结构匹配(属性名称也应该匹配),然后MVC中的模型绑定器会小心地使用您发送的JSON数据填充服务器端模型.你可以阅读更多关于模型粘合剂这里.