我开发了地址控制,其中包含2个DropDownLists(用于城市和国家)和几个TextBox。第二个DropDownList DataSource依赖于第一个DropDownList数据源。
<fieldset>
<legend><%=Title%></legend>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<label for="<%=ddlCountry.ClientID %>">Country</label>
<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>
背后的代码
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();
}
效果很好。但是,如果页面上的其他控件导致PostBack,则ddlCity中的SelectedValue设置为第一个(默认)值。
我该如何避免呢?
答案 0 :(得分:3)
将Page_Init
上的代码移至Page_Load
并将其放入!IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCountry.DataBind();
ddlCity.DataSource = Facade.Addresses.GetCities(countryId);
ddlCity.DataBind();
}
}
答案 1 :(得分:0)
把ddlCountry.DataBind();在条件内