UpdatePanel重新加载整个页面

时间:2010-04-07 14:04:05

标签: c# asp.net updatepanel

我正在构建一个asp.net cutom控件,里面有两个下拉列表:companyIdSelection和productFamilySelection.I在Page_Load填充companyIdSelection,并根据companyIdSelection中的选定项填充productFamilySelection。我正在使用UpdatePanels实现这一点,但由于某种原因每次我更新companyIdSelection Page_Load被调用(据我所知,只有在重新加载整个页面时才会发生),列表将再次重新加载,用户选择的项目将丢失(所选项目始终是最重要的项目。)这是代码

    <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();
}

另外,我尝试将UpdatePanel的UpdateMode设置为“Conditional”并添加asyncpostback触发器 但结果是一样的。 我做错了什么?

PS: 我通过在Page_Load方法中使用Page.IsPostBack修复了更新问题,但我仍然希望尽可能避免完整的回发

2 个答案:

答案 0 :(得分:12)

我认为您误解了UpdatePanel的工作原理。他们实际上做了整页回发,只是在渲染阶段他们只捕获一部分输出并将其发送回AJAX响应,以便页面可以更新。 More info here.

因此,您仍然需要检查它是否是page_load事件中的回发,并且仅在不是数据加载时才执行数据加载。

答案 1 :(得分:2)

更新面板回调将在每次回调时进行页面加载。从表面上看,拉页生命周期(减去渲染和预渲染)将会发生。更新面板给出了ajax的外观,但是您的客户端代码仍然会回发到同一页面 - 这就是您所描述的问题。如果您可以避免使用更新面板,我建议您这样做。使用类似jQuery的东西。如果没有,请在Page_Load

中使用它
if (Page.IsCallback) { } //Do callback specific code here
else { } //Do Postback specific code here

希望这会有所帮助。祝你好运。