【问题标题】:Getting information from a cookie to hide rows from a gridview in MVC3从 cookie 中获取信息以在 MVC3 中的 gridview 中隐藏行
【发布时间】:2012-05-05 14:21:15
【问题描述】:

我正在尝试返回一个视图,该视图排除了用户单击隐藏的行,并生成了一个 cookie,用于存储用户希望隐藏哪些行的信息。

我的问题是 cookie 只包含一个值,因此我的 select 语句一次只排除一行。这是我所拥有的:

public ActionResult Hide(int id)
    {
        HttpCookie cookie = new HttpCookie("HideCookie");
        cookie.Value = id.ToString();
        cookie.Expires = DateTime.Now.AddYears(1);
        System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

        int i = Convert.ToInt32(Request.Cookies.Get("HideCookie").Value);
        var quotes = from q in db.View1 where !q.Quote_ID.Equals(i) select q;

        return View(quotes.ToList());
     }

我已经尝试创建一个字符串并不断将新值附加到该字符串,但它仍然只需要最后一次单击的值。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 cookies session-cookies httpcookie


    【解决方案1】:

    我不认为 cookie 是执行此操作的最佳方法(您是否考虑过使用 TempData,或者至少使用 Session 对象,以便您只向每个用户发送一个 cookie?)虽然使用这种方法,但似乎您可以通过对 cookie 对象使用逗号分隔的列表来做到这一点。

    public ActionResult Hide(int id)
    {
        var cookie = Request.Cookies.Get("HideCookie");
        List<string> hideItems;
        if (cookie == null)
        {
            cookie = new HttpCookie("HideCookie");
            hideItems = new List<string>() { id.ToString() };
            cookie.Value = id.ToString();
            cookie.Expires = DateTime.Now.AddYears(1);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
        }
        else
        {
            cookie = Request.Cookies.Get("HideCookie");
            hideItems = cookie.Value.Split(',').ToList();
            hideItems.Add(id.ToString());
            cookie.Value = string.Join(",", hideItems);
        }
    
        var quotes = from q in db.View1 where 
            !hideItems.Select(i=>int.Parse(i)).Contains(q.Quote_ID) select q;
    
        return View(quotes.ToList());
     }
    

    【讨论】:

    • 感谢您的回复。作业要求我使用 cookie 来隐藏,所以我别无选择。我不得不稍微更改 split 和 join 方法以使语法正常工作。 hideItems = cookie.Value.Split(',').ToList(); cookie.Value = string.Join(",", hideItems.ToArray());我无法让视图返回,因为 hideItems 是一个字符串,而 Quote_ID 是一个 int 并且无法比较。我得到“LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且此方法无法转换为存储表达式。”当我尝试对其使用 ToString 方法时
    • @user1354780 啊对...请查看更新。您可以在进行比较之前将 list 转换为 list
    • 看起来我还有一些错别字(在 string.join 和 string.split 中)。现在应该修好了……看来我需要更多的咖啡:-(
    • 我仍然有错误“LINQ to Entities 无法识别方法 'Int32 Parse(System.String)' 方法,并且此方法无法转换为存储表达式。”您给出的 where 子句似乎使 var 引号不再是 select 语句。当我调试它时,它的值是 {System.Data.Entity.Infrastructure.DbQuery}
    • 我创建了一个包含整数的新列表,并使用 foreach 循环将值从 hideItems 发送到我的整数列表。我可以使用代码: var quotes = from db.View1 中的 !hide.Contains(q.Quote_ID) select q;现在的问题是它一次只隐藏一行,即最后一次单击的 quote_ID。之前隐藏的那个又出现了。编辑:我让它工作了,看来我需要在 else 语句的末尾再次添加 cookie。感谢你的帮助。现在就像一个魅力。
    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 2011-05-06
    • 2013-07-19
    • 2012-06-02
    • 2021-10-30
    • 1970-01-01
    • 2012-08-25
    • 2021-12-07
    相关资源
    最近更新 更多