C# – UpdatePanel reloads the whole page

asp.netcupdatepanel

I'm building an asp.net cutom control inside which I have two dropdownlists: companyIdSelection and productFamilySelection.I populate the companyIdSelection at Page_Load and in order to populate the productFamilySelection depending on the selected item in companyIdSelection.I'm using UpdatePanels to achieve this, but for some reason every time I update companyIdSelection Page_Load is being called ( which as far as I know should happen only when the entire page is reloaded ), the list is being reloaded again and the item the user selected is lost( the selected item is always the top one ).Here's the code

    <asp:UpdatePanel ID="updateFamilies" 
                     runat="server" 
                     UpdateMode="Always">           
        <ContentTemplate>
            Company ID:<br>
            <br></br>
            <asp:DropDownList ID="companyIdSelection" 
                              runat="server" 
                              AutoPostBack="True" 
                              OnSelectedIndexChanged="companyIdSelection_SelectedIndexChanged">
            </asp:DropDownList>
            <br></br>
            Product Family:
            <br></br>
            <asp:DropDownList ID="productFamilySelection" runat="server" 
                              AutoPostBack="True" 
                              onselectedindexchanged="productFamilySelection_SelectedIndexChanged">
            </asp:DropDownList>
            <br>
        </ContentTemplate>                 
    </asp:UpdatePanel>

protected void Page_Load(object sender, EventArgs e)
{
    this.companyIdSelection.DataSource = companyIds(); //companyIds returns the object containing the initial data items
    this.companyIdSelection.DataBind();
}

protected void companyIdSelection_SelectedIndexChanged(object sender, EventArgs e)
{
    // Page_Load is called again for some reason before this method is called, so it 
    // resets the companyIdSelection
    EngDbService s = new EngDbService();
    productFamilySelection.DataSource = s.getProductFamilies(companyIdSelection.Text);
    productFamilySelection.DataBind();
}

Also, I tried setting the UpdateMode of the UpdatePanel to "Conditional" and adding an asyncpostback trigger
but the result was the same.
What am I doing wrong?

PS:
I fixed the updating problem, by using Page.IsPostBack in the Page_Load method, but I would still want to avoid a full postback if possible

Best Answer

I think you misunderstand how UpdatePanels work. They DO actually do a full page postback, it's just that during the rendering stage they capture only a portion of the output and send it back in the AJAX response so the page can be updated. More info here.

So you will still need to check whether it is a postback in your page_load event and only perform your data load if it isn't one.

Related Topic