How to process an array of objects in a session

In the project I'm working on, I have a list List<Item>with objects that are saved in the session.Session.Add("SessionName", List);

In the controller, I create a viewModel with 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 loop I go through the list of elements and make a form for all of them to remove the element.

<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 a message from the send button is handeld, the item is removed from the array and sent back the same way as viewModel (with 1 item less in itemList).

return View("view.ascx", viewModel);

When the message is processed and the view reloads the value of html.Hidden and Html.Textbox, this is the value of the deleted item. The html.Encode value is the correct value. When I reload the page, the correct values ​​are in the fields. Both times I create a viewModel in exactly the same way.

. .

Thanx

+3
1

, URL. ASP.NET , , , URL. , , , , . ASP.NET.

, , , - URL- . , AJAX.

+1

Source: https://habr.com/ru/post/1740328/


All Articles