ASP.NET: Page is rendered without change on Post-back even when changed

494 Views Asked by At

I have a page which contains the generated content.

Page.aspx:

<asp:DropDownList ID="cmbUsers" runat="server" AutoPostBack="True" 
    oninit="cmbUsers_Init">
</asp:DropDownList>
<asp:Panel ID="pnlRights" runat="server">

Page.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    string [] roles = Roles.GetAllRoles();
    string sel_user = ... ; // get the user name selected by combo

    foreach (string role in roles)
    {
        CheckBox chk = new CheckBox();
        chk.Text = role;
        chk.Checked = Roles.IsUserInRole(sel_user, role);
        pnlRights.Controls.Add(chk);

    }
}
protected void cmbUsers_Init(object sender, EventArgs e)
{
            ... // fill the combo with user list

    if (!IsPostBack)
    {
        {
            cmbUsers.SelectedValue = // the current signed username;
        }
    }
}

On the first load the page is correct - all checkboxes are set as they should be (the roles where user is in are checked). The problem happens when you change the user in combo. After change the postback is called, all checkboxes are set correctly again (saw in debugger), BUT the browser shows the checkboxes set to previous user. I do not suspect browser mistake (tried in IE, Maxthon, Mozilla), but some setting I forget to set. Is it something with caching? Could you give me some hint, please?

1

There are 1 best solutions below

3
On BEST ANSWER

Your rebuilding the page to a fresh state each postback. Check the IsPostBack property of the Page object to insure you only init the page once.

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        string [] roles = Roles.GetAllRoles();
        string sel_user = ... ; // get the user name selected by combo

        foreach (string role in roles)
        {
            CheckBox chk = new CheckBox();
            chk.Text = role;
            chk.Checked = Roles.IsUserInRole(sel_user, role);
            pnlRights.Controls.Add(chk);

        }
    }
}

Edit - Looking at your example again, this won't work exactly, you should have a button or something that is generating the postback, and do your response logic there, not in the page_load. This is the reason your seeing this behavior though.