tags:

views:

126

answers:

3

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.

+1  A: 

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.

eulerfx
Thank you! That did the trick. On another note, is there better way to do this? I am not a big fan of building "name" dynamically to achieve this.
Thomas
You can create html helper methods for building input elements using lambda expressions and html helper methods for building input elements for a collection as well.
eulerfx
A: 

Hi, Can you post a complete example for this one.

Thanks

Altaf
A: 

Hi Can you please post the complete example.

ASP.NET MVC Maniac