Get ViewData IList back on postback in ASP.NET MVC
I have the following in my view:
<%using (Html.BeginForm()) {%>
<% foreach (var item in Model.Cart) { %>
<div>
<%= Html.TextBox("Cart.Quantity", item.Quantity, new { maxlength = "2" })%>
<%= Html.Hidden("Cart.ItemID", item.ItemID)%>
</div>
<% } %>
<input name="update" type="image" src="image.gif" />
I then have this code in my controller:
public ActionResult Index()
{
开发者_运维技巧 CartViewData cartViewData = new CartViewData();
IList<Item> items = ItemManager.GetItems();
cartViewData.Cart = items;
return View("Index", cartViewData);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(CartViewData cartViewData)
{
// cartviewData is null
}
Is there a way to grab the List on the postback to see if the values in the textboxes have changed?
Thanks
Below is a simplified example since it was requested:
<% for (int i = 0; i < Model.Cart.Count; i++ ) { %>
<a href="javascript:void(0);" onclick="removeItem(<%= Model.Cart[i].ShoppingCartItemID %>);">Remove</a>
<% } %>
Hope this helps.
This simplest way is to do this - name each cart item control with this format:
<input type="text" name="Items[0].Quantity" />
Where the 0 corresponds to the index of the item in the items collection. Next, move the items collection to a property on the cart, so that you model looks something like this:
class CartViewData
{
public CartViewData()
{
this.Items = new List<Item>();
}
public IList<Item> Items { get; private set; }
class Item
{
public int Quantity { get; set; }
}
}
Then the DefaultModelBinder will bind the values to the model.
精彩评论