how to handle a array of objects in a session
        Posted  
        
            by Robert
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Robert
        
        
        
        Published on 2010-04-08T14:59:32Z
        Indexed on 
            2010/04/08
            15:03 UTC
        
        
        Read the original article
        Hit count: 318
        
Hello,
In the project I'm working on I have got a list List<Item> with objects that Is saved in a session. Session.Add("SessionName", List);
In the Controller I build a viewModel with the data from this session
var arrayList = (List<Item>)Session["SessionName"];
var arrayListItems= new List<CartItem>();
foreach (var item in arrayList)
            {
                var listItem = new Item
                                   {
                                       Amount = item.Amount, 
                                       Variant= item.variant, 
                                       Id = item.Id
                                   };
                arrayListItems.Add(listItem);
            }
var viewModel = new DetailViewModel
            {
                itemList = arrayListItems
            }
and in my View I loop trough the list of Items and make a form for all of them to be able to remove the item.
<table>
    <%foreach (var Item in Model.itemList) { %>
       <% using (Html.BeginForm()) { %>
           <tr>     
              <td><%=Html.Hidden(Settings.Prefix + ".VariantId", Item .Variant.Id)%>
              <td> <%=Html.TextBox(Settings.Prefix + ".Amount", Item.Amount)%></td>
              <td> <%=Html.Encode(Item.Amount)%> </td>
              <td> <input type="submit" value="Remove" /> </td>
           </tr>
      <% } %> 
    <% } %> 
</table>
When the post from the submit button is handeld the item is removed from the array and post back exactly the same viewModel (with 1 item less in the itemList).
return View("view.ascx", viewModel);
When the post is handled and the view has reloaded the value's of the html.Hidden and Html.Textbox are the value's of the removed item. The value of the html.Encode is the correct value. When i reload the page the correct values are in the fields. Both times i build the viewModel the exact same way.
I cant find the cause or solution of this error. I would be very happy with any help to solve this problem
Thanx in advance for any tips or help
© Stack Overflow or respective owner