Topic: Persisting Session to the View
Share/Save/Bookmark
Description: This code will demonstrate how Session objects can be persisted to the View in an MVC applications

Notes:
There are three objects that this code is working with.
   1.  ShoppingCart (this is a container for ShoppingCartItems)
   2.  ShoppingCartItem (this object has details about the item in the cart)
   3.  Product (used to get information to populate the ShoppingCartItem)

In the Global.asax, you can set Session as in the example below for a shopping Cart

        protected void Session_Start(Object sender, EventArgs e)
        {
            Session[Constants.SHOPPING_CART_KEY] = new ShoppingCart();
        } 
The key is stored in a class that contains constants:

    public class Constants
    {
        public const string SHOPPING_CART_KEY = "SHOPPING_CART";
    }
You can then populate the Session object, as needed in any controller:

    ShoppingCart shoppingCart = (ShoppingCart)Session[Constants.SHOPPING_CART_KEY];
 
    Product product = new Product();
 
    product.Id = 11;
    product.Price = 11.23;
    product.Name = "My Product Name";
 
    shoppingCart.AddItem(product, productType);


    
return RedirectToAction("MyView");

When you navigate to your view, you can access the object inside the session, as follows:

  <%
      ShoppingCart cart = (ShoppingCart)Session[Constants.SHOPPING_CART_KEY];
  %>

<%=cart.TotalPrice()%>

or

    <table border="1" style="width:100%">
      <tr>
         <th>Product</th>
         <th>Price</th>
         <th>Quantity</th>
         <th>Add</th>
         <th>Remove</th>
      </tr>

  <%
      foreach (ShoppingCartItem item in cart.Items)
      {
         Product product = (Product)item.Product;
  %>    
      <tr>
          <td><%=product.Name%></td>
          <td><%=product.Price%></td>
          <td><%=item.Quantity%></td>
          <td><%=Html.ActionLink("Add""Add"new { controller = "ShoppingCart", id = product.Id, productType = ProductType.Music })%></td>
          <td><%=Html.ActionLink("Remove""Remove"new { controller = "ShoppingCart", id = product.Id, productType = ProductType.Music })%></td>
      </tr>  
  <%        
      }
  %>  
  </table>