views:

341

answers:

2

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!

+4  A: 

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.

David McEwing
Oh, I thought that it would call the method, then refresh the page, calling page_load... Is there a way to fix this?
marcgg
Set the font size on the client with Javascript. Or do another redirect to the page. Or look at what the page_load actually needs to do with the cookie and do that from the click event as well.
David McEwing
Thanks for your help! How can I do another redirect to the page? These buttons are on the master page, so I don't know to what page I wan't to redirect. I don't think i can redirect to "". Redirecting to "?" sends me to url.com/page.aspx/? which break.
marcgg
A: 

The first time, the request has no cookies (yet); it will only have them the second time around, after the response has set them. So your code has to deal with the possibility that Request.Cookies just may not have a "fontSize" entry, and provide the proper default when that is the case. For example:

HttpCookie cookie = Request.Cookies.Get("fontSize");
// Check if cookie exists in the current request.
if (cookie == null)
{
   Response.Write( "Defaulting to 'small'.");
}
else
{
   Response.Write( Request.Cookies["fontSize"].Value);
)
Alex Martelli
how do I change this?
marcgg
it's part of the HTTP standard -- you can't realistically change it. Editing my answer to show how to _deal_ with it...
Alex Martelli