首页 新闻 会员 周边

mvc音乐商店的购物的一段代码解析 路过的大侠帮忙看看 谢谢!没什么豆

0
悬赏园豆:5 [已解决问题] 解决于 2013-01-07 17:49

今天仔细了看了它的流程和页面的一些逻辑  发现一个以前不是常用的东西。求大侠解释下谢谢。

图片:

 

代码:

        public ActionResult AddToCart(int id)
        {

            // Retrieve the album from the database
            var addedAlbum = storeDB.Albums
                .Single(album => album.AlbumId == id);

            // Add it to the shopping cart
            var cart = ShoppingCart.GetCart(this.HttpContext);

            cart.AddToCart(addedAlbum);

            // Go back to the main store page for more shopping
            return RedirectToAction("Index");
        }

这一个ShoppingCart.GetCart(this.HttpContext);

的上下文对象,对应的方法。

 public const string CartSessionKey = "CartId";

public static ShoppingCart GetCart(HttpContextBase context) { var cart = new ShoppingCart(); cart.ShoppingCartId = cart.GetCartId(context); return cart; }

 

        // We're using HttpContextBase to allow access to cookies.
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();

                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }

            return context.Session[CartSessionKey].ToString();
        }

之后呈现的页面

不明白他的业务逻辑 就是他这样做的目的 主要是这个上下文对象  。

KyrieYang的主页 KyrieYang | 菜鸟二级 | 园豆:205
提问于:2013-01-06 23:56
< >
分享
最佳答案
0

从 楼主 贴的代码看,不传递 this.HttpContext ,直接在 ShoppingCart 使用这个HttpContext也是可以的。

可能是 这个 ShoppingCart 购物车 毕竟是一个对象,为了到达和HttpContext 解耦,而用HttpContextBase,这样的话,可以很好的进行单元测试。

收获园豆:5
Qlin | 老鸟四级 |园豆:2403 | 2013-01-07 08:43

听你的回答 又在网上看了下 有点明白了 谢谢 也谢谢其他的2位朋友

KyrieYang | 园豆:205 (菜鸟二级) | 2013-01-07 17:47
其他回答(2)
0

解耦

Tom.汤 | 园豆:3028 (老鸟四级) | 2013-01-07 12:47
0

Qlin正解

Nemo_Li | 园豆:6 (初学一级) | 2013-01-07 16:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册