【问题标题】:How create view for show cookie's info in asp.net mvc using razor?如何使用剃刀在 asp.net mvc 中创建显示 cookie 信息的视图?
【发布时间】:2016-04-23 07:23:20
【问题描述】:

我正在使用asp.net mvc 5 开发一个在线商店,我使用cookie 将商品添加到购物车。我想要一个页面来显示选定的项目(在 cookie 中),但我不知道怎么做,我只是为它写了一个名为 Basket 的操作结果。在我看来,我应该使用@model List<BasketVM>,但是什么时候不知道怎么用?!

有人可以帮帮我吗? 谢谢

GoodController

[HttpGet]
    public ActionResult Basket()
    {
        GoodDetailsRepositories blGoodDetails = new GoodDetailsRepositories();
        List<BasketVM> listBasket = new List<BasketVM>();
        List<HttpCookie> lst = new List<HttpCookie>();
        for (int i = Request.Cookies.Count - 1; i >= 0; i--)
        {
            if (lst.Where(p => p.Name == Request.Cookies[i].Name).Any() == false)
                lst.Add(Request.Cookies[i]);
        }
        foreach (var item in lst.Where(p => p.Name.StartsWith("NishtmanCart_")))
        {
            listBasket.Add(new BasketVM {
                GoodDetails = blGoodDetails.Find(Convert.ToInt32(item.Name.Substring(13))), Count =Convert.ToInt32(item.Value) });
        }
        return View(listBasket);
    }

BasketVM.cs

 public class BasketVM
{
    public NP1.Models.GoodDetail GoodDetails { get; set; }
    public int Count { get; set; }
}

GoodDetails.cs

public partial class GoodDetail
{
    public GoodDetail()
    {
        this.FactorItems = new HashSet<FactorItem>();
    }

    public int DetailsGoodID { get; set; }
    public int FKSubGoods { get; set; }
    public string NishtmanCode { get; set; }
    public string DetailsColor { get; set; }
    public string DetailsExist { get; set; }
    public long DetailsNowPrice { get; set; }
    public Nullable<long> DetailsPrePrice { get; set; }
    public string DetailsName { get; set; }
    public string DetailsLeatherType { get; set; }
    public string DetailsWeight { get; set; }
    public string DetailsSize { get; set; }
    public string DetailsProducer { get; set; }
    public string DetailsExtraInfo { get; set; }
    public string DetailsURL { get; set; }
    public string DetailsKeyWords { get; set; }
    public string DetailsTags { get; set; }
    public int DetailsLike { get; set; }
    public int DetailsDisLike { get; set; }
    public string DetailsImage1 { get; set; }
    public string DetailsSmallImage1 { get; set; }
    public string DetailsImage2 { get; set; }
    public string DetailsSmallImage2 { get; set; }
    public string DetailsImage3 { get; set; }
    public string DetailsSmallImage3 { get; set; }
    public string DetailsImage4 { get; set; }
    public string DetailsSmallImage4 { get; set; }

    public virtual SubGood SubGood { get; set; }
    public virtual ICollection<FactorItem> FactorItems { get; set; }
}

加入购物车代码

public ActionResult AddToCart (int Id , int Count)
    {
        try
        {
            if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
        {
            //Edit cookie
            var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
            cookie.Expires = DateTime.Now.AddMonths(1);
            cookie.HttpOnly = true;
            Response.Cookies.Set(cookie);

        }
        else
        {
            //Add new cookie
            var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
            cookie.Expires = DateTime.Now.AddMonths(1);
            cookie.HttpOnly = true;
            Response.Cookies.Add(cookie);
        }
            List<HttpCookie> lst = new List<HttpCookie>();
            for (int i = 0; i < Request.Cookies.Count; i++ )
            {
                lst.Add(Request.Cookies[i]);
            }

            bool isGet = Request.HttpMethod == "GET";
            int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
            return Json(new MyJsonData()
            {
                Success = true,
                Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,

                Html = "cart items (" + CartCount.ToString() + ")"
            }
                );
        }
        catch(Exception)
        {
            return Json(new MyJsonData()
            {
                Success = false,

                Script = "alert('Good didn't add');",
                Html = ""
            }
                );

        }

    }

【问题讨论】:

  • 我更新了我的帖子亲爱的@Anonymous
  • 那么更好的方法是什么?我想显示一些 GoodDetails 字段和相关的 cookie 。我的意思是购物车物品的数量。 @匿名
  • 你的结构很好,但你可以在会话中存储这些东西。随着项目的添加、删除或更新,可以轻松修改会话
  • 你是对的,但是如果我使用会话,用户应该先注册然后他们才能购物?这是正确的 ? @匿名
  • 没必要,不用登录也可以保持会话

标签: asp.net-mvc razor cookies model viewmodel


【解决方案1】:

你用什么名字保存cookies你可以这样检索假设用户ID你想休息你写的东西会起作用:

    if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
    {
        HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
        // retrieve cookie data here
    }

how to call in view :

Viewbag.userid = @Request.Cookies["Userid"].value

In order to read a cookie client-side it needs to be created with the HttpOnly flag set to false.
Please go thorugh the below already asked question. 

MVC Access stored cookie

【讨论】:

  • 谢谢亲爱的,但我也不知道如何创建视图来显示它
  • 你能写一个显示retrieve cookie data的例子吗?!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 2016-01-28
  • 1970-01-01
  • 2021-03-14
  • 2016-05-10
  • 1970-01-01
  • 2017-10-12
相关资源
最近更新 更多