Search code examples
c#asp.netcookiespostbackpageload

Cookie not being handled when Page_Load() fires


My problem is that when i press my button(which causes a postback) the cookie that is made in the click_event isn't being handled in a method I call in the Page_Load.

Here is the code:

//Page_Load
protected void Page_Load(object sender, EventArgs e)
{
    if(!Context.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
    }
    loadCookies();
}
//loadCookies
public void loadCookies()
{
    for (int i = 0; i < 40; i++ )
    {
        if(Request.Cookies["FiscaleTable" + i.ToString()] != null){
           TableRow row = new TableRow();
           for (int i2 = 0; i2 < 10; i2++ )
           {
                TableCell cell = new TableCell();
                cell.Text = Request.Cookies["FiscaleTable" + i.ToString()][i2.ToString()];
                row.Cells.Add(cell);
            }
            FiscaleEenhedenTable.Rows.Add(row);
        }
    }
}
//Button_Click
public void makeFiscaleEenhedenCookie(object sender, EventArgs e)
{
    ContentPlaceHolder Content;
    Content = (ContentPlaceHolder)Master.FindControl("MainContent");
    HttpCookie FiscaleEenhedenCookie = new HttpCookie("FiscaleTable" + (FiscaleEenhedenTable.Rows.Count - 1).ToString());
    FiscaleEenhedenCookie.Expires = DateTime.Now.AddDays(1d);
    for (int i2 = 0; i2 < 10; i2++ )
    {
        TextBox temp = (TextBox)Content.FindControl("FiscaleUnitTextBox" + (i2 + 1).ToString());
        FiscaleEenhedenCookie[i2.ToString()] = temp.Text;
    }
    Response.Cookies.Add(FiscaleEenhedenCookie);
}
//Button
<asp:Button ID="FiscaleAddButton" runat="server" CommandName="FiAdd" Text="Toevoegen" ClientIDMode="Static" OnClick="makeFiscaleEenhedenCookie"/>

As soon as I call another postback or refresh the page the cookie is being handled. I have no idea why this is happening. Any help would be helpfull.


Solution

  • It is the expected behaviour. When button is clicked a postback is done. Page_Load is executed, then makeFisicalEenhedenCookie is executed, the page renders and it is sent to the user along with the cookie you set in the response. When another postback is done, the user sent the cookie to the server and you can handle it. It is basic flow of the asp.net page lifecycle.

    In a few words: If you set a cookie in a response you can not query for the cookie until the next request.