最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net mvc 3 - How can I bind a simple Javascript array to an MVC3 controller action method? - Stack Overflow

programmeradmin0浏览0评论

Here is the javascript code I use to create the array and send it on it's way:

<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>

The items object is properly constructed with the values I need.

What data type must my object be on the backend of my controller?

I tried this but the variable remains null and is not bound.

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

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

Here is the javascript code I use to create the array and send it on it's way:

<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>

The items object is properly constructed with the values I need.

What data type must my object be on the backend of my controller?

I tried this but the variable remains null and is not bound.

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

    // Some magic here.
    return RedirectToAction("Index");
}
Share Improve this question asked Apr 6, 2012 at 16:31 Only Bolivian HereOnly Bolivian Here 36.8k65 gold badges166 silver badges257 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

If you are going to send JSON to the server you need to JSON.stringify the data and specify the contentType as application/json to play nice with the MVC3 model binder:

    $.ajax({
            type: "POST",
            url: "@Url.Action("UpdateCart", "Cart")",
            data: JSON.stringify(items),
            success: function () {
                alert("Successfully updated your cart!");
            },
            contentType: 'application/json'
        });

And as the datatype on the server you can use strongly typed classes eg:

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");
}

But you need to tweak the items list a bit:

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 });
});

Basically the JSON object structure should match the C# model class structure (also the property name should match) and then the model binder in MVC takes care to populate your server side models with the JSON data that you've sent. You can read more about model binders here.

发布评论

评论列表(0)

  1. 暂无评论