How can I bind a simple Javascript array to an MVC3 controller action method?
- by Sergio Tapia
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");
}