views:

90

answers:

1

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 and help

+1  A: 

This happens because you are posting back to the same URL. ASP.NET has a built in mechanism to make sure that values from form inputs are always returned to the browser the same as they are sent in when posting back to the same URL. This can be a very annoying behavior, I agree, but there is likely a lengthy discussion of rationale for it somewhere. For starters, it would break the auto populate with same values on validation feature of ASP.NET.

The easiest way I have found to get past the problem is to just post to a different URL and redirect back. You can also fix the problem by handling the request via AJAX.

NickLarsen