How can I bind a simple Javascript array to an MVC3 controller action method?
Posted
by
Sergio Tapia
on Stack Overflow
See other posts from Stack Overflow
or by Sergio Tapia
Published on 2012-04-06T16:31:08Z
Indexed on
2012/04/06
17:29 UTC
Read the original article
Hit count: 255
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");
}
© Stack Overflow or respective owner