【问题标题】:Show banner once per browser session using asp.net and cookies使用 asp.net 和 cookie 在每个浏览器会话中显示一次横幅
【发布时间】:2018-01-11 06:35:30
【问题描述】:

我只想在每个浏览器会话中显示一次横幅。

 <asp:Panel ID="Panel1" runat="server">
<img src="path"/>
 </asp:Panel>

我想使用代码隐藏文件中的 cookie 来实现这一点。

我的代码在下面,但横幅一直显示,我如何以投注方式实现这一目标

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    //Set Banner Cookie
    HttpCookie BannerCookie = new HttpCookie("ShowBanner");
    BannerCookie.Value = "YES";
     Response.Cookies.Add(bannercookie)
     Panel1.Visible = False;
    //Do Somthing...
    ShowPageDetails();
    ShowBanner();

    }
    else
    {
    //Do Somthing
    Panel1.Visible = False;
    ShowPageDetails();
    ShowBanner();
    }
}

public void ShowBanner()
{
 HttpCookie BannerCookie = Request.Cookies["ShowBanner"];
 if (BannerCookie != null)
 {
 Panel1.Visible = True;
            BannerCookie.Value = null;
            Response.Cookies.Add(BannerCookie);
 }
else
{
Panel1.Visible = false;
}
}

更新:我尝试了Ajay 下面提到的解决方案,但它无法正常工作,要么在 cookie 为空时生成错误,要么总是显示横幅。

我不确定如何更改逻辑,以便横幅在每个浏览器会话中只显示一个。我尝试了几种方法,但没有得到它的工作。任何其他可能在代码隐藏中工作的解决方案。

【问题讨论】:

  • 你在哪里添加cookie作为响应:Response.Cookies.Add(bannercookie)?
  • 对不起错过了那部分...复制时..我现在会更新它。
  • 我在页面加载时设置 cookie 的值,当我显示横幅时,我将 cookie 设置为空值....但它没有按预期工作。我在逻辑上做错了什么。
  • 检查我的答案中的显示横幅代码。

标签: c# asp.net webforms


【解决方案1】:

你的 ShowBanner() 逻辑需要更正,当 cookie 不存在时显示,否则你不做反向操作,页面加载时也不要每次都添加 cookie

我只想在每个浏览器会话中显示一次横幅。

我想使用代码隐藏文件中的 cookie 来实现这一点。

我的代码在下面,但横幅一直显示,我如何以投注方式实现这一目标

public void ShowBanner()
{
 HttpCookie BannerCookie = Request.Cookies["ShowBanner"];
 if (BannerCookie != null)
 {
 Panel1.Visible = false;
 }
else{
Panel1.Visible = true;
}
}

在页面加载时仅在不存在时添加 cookie

HttpCookie BannerCookie = Request.Cookies["ShowBanner"];
 if (BannerCookie == null)
{
    BannerCookie = new HttpCookie("ShowBanner");
    BannerCookie.Value = "YES";
     Response.Cookies.Add(bannercookie)
}

【讨论】:

  • 在页面加载部分代码上这行代码HttpCookie BannerCookie = new HttpCookie("ShowBanner");给我错误“不能在此范围内声明局部变量......”
  • 编辑代码,如果在ShowBanner()中不需要再次声明HttpCookie
  • 但是错误是你提到的代码的第二部分......不是 showbanner() 部分错误描述A local variable named 'BannerCookie' cannot be declared in this scope because it would give a different meaning to 'BannerCookie', which is already used in a 'parent or current' scope to denote something else
【解决方案2】:

创建会话变量:

    if(Session["whatever"] == null)
    {
         // show the post
    }
    else
    {
         Session["whatever"] = 0;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2023-04-11
    • 2015-03-09
    相关资源
    最近更新 更多