在视图页面中检索会话值

retrieve session value in view page

我刚开始学习如何建立网站,但在使用会话创建购物车时遇到了一些问题。

这是我的模型代码:

public class Cart
{
    public Cart()
    {
        Products = new List<ProductStock>();
    }

    public List<ProductStock> Products { get; set; }

    public void AddToCart(Product product, Store store, int quantity)
    {
        Products.Add(new ProductStock
        {
            ProductID = product.ProductID,
            Product = product,
            StoreID = store.StoreID,
            Store = store,
            Quantity = quantity
        });
    }
}

这是控制器代码,我想在视图页面中使用的会话称为 "cart":

public class CartController : Controller
{
    private MagicInventoryEntities db = new MagicInventoryEntities();

    public ActionResult Index()
    {
        Cart cart = (Cart) Session["cart"];

        return View(cart);
    }

    [HttpPost]
    public ActionResult AddToCart(int productID, int storeID, int quantity)
    {
        Product product = db.Products.Find(productID);
        Store store = db.Stores.Find(storeID);

        Cart cart = (Cart) Session["cart"];

        cart.AddToCart(product, store, quantity);

        return new RedirectToRouteResult(new RouteValueDictionary(
        new
        {
            action = "Index",
            controller = "Cart"
        }));
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

这段代码是我老师的,我的笔记不是很清楚,我没有足够的时间来写关于视图页面的细节。他说他会在星期一再次展示这个过程,我只是不想等待,我想弄清楚并继续前进。我只知道调用会话的基本方法是“@session["SessionName"].ToString()”。我已经在我的方法( session["testing"]=ProductID )中尝试过了,我可以得到这个值。但是,我不知道如何从 Session["cart"].

中获取价值

假设您在会话中保存了一个购物车类型的对象,为了检索该对象,您可以在索引视图中使用以下代码:

 @{
    Cart cart = HttpContext.Current.Session["Cart"] as Cart;
  }

但是,我看到 CartController 中的 Index 方法已经从 Session 中检索对象并将其传递给 Index 视图。为了访问它,您必须在索引视图中编写以下代码:

@model {ProjectName}.Models.Cart  //you tell the View what type of object it should expect to receive; instead of {ProjectName} write your project name


@foreach(var product in Model.Products) {  //you access the received object by using the keyword Model
    <div>
        @product.ProductId
    </div>
}

如您所见,此示例为产品列表中每个 ProductStock 类型的项目创建一个 div,并将当前 ProductStock ProductId 的值写入其中。

如果您的 Session 中没有保存 Cart 类型的对象,您可以将以下代码添加到您的 Index 方法中:

if(Session["Cart"] == null)
{
    var cart = new Cart();
    Session["Cart"] = cart;
}

Cart cart = (Cart) Session["cart"];
return View(cart);