开发者

DropDownList and Update Panel

I develop address control, which contains 2 DropDownLists (for cities and countries) and several TextBoxes. The second DropDownList DataSource depends on the first DropDownList DataSource.

<fieldset>
 <legend><%=Title%></legend>
  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <div>
            <label for="<%=ddlCountry.ClientID %>">Country</label>
      开发者_StackOverflow中文版      <asp:DropDownList runat="server" ID="ddlCountry" 
              DataTextField="Name" DataValueField="Id" 
              DataSource="<%#Facade.Addresses.GetCountries() %>"
              AutoPostBack="true" 
              OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"
            />
        </div>
        <div>
            <label for="<%=ddlCity.ClientID %>">City</label>
            <asp:DropDownList runat="server" ID="ddlCity" 
                DataTextField="Name"   DataValueField="Name" />
        </div>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlCountry" EventName="SelectedIndexChanged" />
    </Triggers>
</asp:UpdatePanel>
<div>
    <label for="<%=txtStreet.ClientID %>">Street</label>
    <uc:TextBox ID="txtStreet" Text="<%#Address.Street %>" runat="server" />
</div>
<div>
    <label for="<%=txtBlock.ClientID %>">Block</label>
    <uc:TextBox ID="txtBlock" Text="<%#Address.Block %>" runat="server" />
</div>
<div>
</fieldset> 

Code Behind

protected void Page_Init(object sender, EventArgs e)
  {

    ddlCountry.DataBind();
     if (!IsPostBack)
       {
         ddlCity.DataSource = Facade.Addresses.GetCities(countryId);
         ddlCity.DataBind();
      }

}

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
  {
     ddlCity.DataSource = Facade.Addresses.GetCities(countryId);
     ddlCity.DataBind();
 }

It works good. But if other control on the page causes PostBack, when the SelectedValue in ddlCity sets to the first (default) value.

How do I avoid it?


Move the code on Page_Init to Page_Load and put it inside !IsPostBack

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlCountry.DataBind();
        ddlCity.DataSource = Facade.Addresses.GetCities(countryId);
        ddlCity.DataBind();
    }
}


put ddlCountry.DataBind(); inside if condition

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜