C# – Cookie only displayed on refresh

asp.netc++cookies

I have some trouble understanding this one so here it is.

I'm trying to set a cookie and display the value on the page using ASP.NET + C#.

here's my code:

protected void lbChangeToSmall_Click(object sender, EventArgs e)
        {
            Response.Cookies["fontSize"].Value = "small";
        }

and

<asp:LinkButton runat="server" id="lbChangeToSmall" Text="A" CssClass="txt-sm" OnClick="lbChangeToSmall_Click"></asp:LinkButton>

And finally

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Response.Write( Request.Cookies["fontSize"].Value);
            }

        }

When I click on the button, nothing is displayed on the page, but the cookie is actually set. If I refresh the page, the cookie displays.

So it seems that the cookie is set correctly but the application is not able to read it right away.

I tried to get rid of the if(postBack):

 protected void Page_Load(object sender, EventArgs e)
        {
                Response.Write( Request.Cookies["virgilFontSize"].Value);
        }

but it didn't change a thing.

What am I doing wrong?

Thanks!

Best Solution

The lblChangeToSmall_Click event is fired after the Page_Load event. Therefore the cookie write won't be available on the Request until the subsequent postback.

It will be avaialable on the client immediately though.

Related Question