MVC中的cookie需要2页加载才能注册

时间:2015-01-27 19:07:51

标签: c# asp.net-mvc cookies

我正在创建一个MVC应用程序,其中我有一个显示隐藏值和隐藏值的按钮。问题是,我需要在cookie更改注册页面之前按两次按钮。任何帮助都会很棒,特别是如果你告诉我如何纠正这个问题。

所以这里发生的事情是我必须按两次Show Not Active才能让它改为Hide Not Active,反之亦然。

if (Request.Cookies["showHidden"] != null)
{
    ViewBag.Show = Request.Cookies["showHidden"].Value;
}
else
{
    ViewBag.Show = "false"
}
@if (User.IsInRole("Data Manager"))
{
    if (ViewBag.Show != "true")
    {
        <text>
            @Html.ActionLink("Show Not Active", "Details", new
              { show = "true" }, new { @class="btn btn-primary btn-sm"                })
       </text>
    }
    else
    {
        <text>   
            @Html.ActionLink("Hide Not Active", "Details", new 
              { show = "false" }, new { @class="btn btn-primary btn-                  sm })
       </text>
    }
public ActionResult Details(int? id, string show)
{
    if (show == "true")
    {
        if (this.Response.Cookies["showHidden"] == null
        {
            HttpCookie cookie = new HttpCookie("showHidden", "true");
            cookie.Expires = new DateTime(DateTime.Now.Year + 1, DateTime.Now.Month, DateTime.Now.Day);
            this.Response.Cookies.Add(cookie);
        }
        else
        {            
            HttpCookie cookie = new HttpCookie("showHidden", "true");
            cookie.Expires = new DateTime(DateTime.Now.Year + 1, DateTime.Now.Month, DateTime.Now.Day);
            this.Response.SetCookie(cookie);        
        }
    }
    if (show == "false")
    {        
        if (this.Response.Cookies["showHidden"] == null
        {
            HttpCookie cookie = new HttpCookie("showHidden", "false");
            cookie.Expires = new DateTime(DateTime.Now.Year + 1, DateTime.Now.Month, DateTime.Now.Day);
            this.Response.Cookies.Add(cookie);
        }
        else
        {            
            HttpCookie cookie = new HttpCookie("showHidden", "false");
            cookie.Expires = new DateTime(DateTime.Now.Year + 1, DateTime.Now.Month, DateTime.Now.Day);
            this.Response.SetCookie(cookie);        
        }

    }
    thing thing = db.thing.Find(id);
    if (thing == null)
    {
        return HttpNotFound();
    }
    return View(thing);
}

1 个答案:

答案 0 :(得分:0)

无论如何,我想出了如何在每次点击时更改按钮以及隐藏/显示每次点击更改,但我现在有另一个问题,每次离开页面时cookie都不会持续存在,所以我将在另一个帖子中发布。