【发布时间】:2011-10-09 23:41:03
【问题描述】:
我开发了地址控件,其中包含 2 个下拉列表(用于城市和国家)和几个文本框。第二个 DropDownList DataSource 依赖于第一个 DropDownList DataSource。
<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 设置为第一个(默认)值时。
如何避免?
【问题讨论】:
-
法哈德有解决方案。 naveen 的建议只是为了符合标准,尽管您只需要 !IsPostback
标签: asp.net ajax webforms drop-down-menu