本功能特点:
下级的显示和数据的加载都是由上一级下拉框的SelectedIndexChanged触发的,在上级下拉框没有选择之前,下级不会出现,用户体验比较好。
无刷新方面,采用AJAX技术,在数据选择的时候,不会造成页面刷新,不会回传整个页面,不影响其他控件。
由于省市区三级数据较大,采用数据库保存数据,代码中需要用到DBHelper来操作数据库。
注意事项:
本代码完全用Asp.net实现,没有使用javascript,可以把功能单独嵌套到ASP页面中,也可以做成用户控件。
由于采用了AJAX无刷新技术,如果嵌入到的页面中包含有ScriptManager控件,需要把本代码中的改为ScriptManagerProxy.
页面代码:
<style type="text/css"> #pro_city_area select{width:78px;} #ddlPro{display:inline;} #ddlCity{display:none;} #ddlArea{display:none;} </style> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <div id="pro_city_area"> <asp:DropDownList ID="ddlPro" runat="server" onselectedindexchanged="ddlPro_SelectedIndexChanged"> </asp:DropDownList> <asp:DropDownList ID="ddlCity" runat="server" onselectedindexchanged="ddlCity_SelectedIndexChanged" ViewStateMode="Enabled"> </asp:DropDownList> <asp:DropDownList ID="ddlArea" runat="server"> </asp:DropDownList> </div> </ContentTemplate> </asp:UpdatePanel> </form>
后置代码:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //加载省份数据 BindProData(); } } DBHelper db = new DBHelper(); //绑定省份数据 private void BindProData() { string sql = "SELECT [id],[provinceID],[province] FROM [Public].[dbo].[Province]"; DataTable dt = db.GetDataTable(sql, null); this.ddlPro.DataSource = dt; this.ddlPro.DataTextField = "province"; this.ddlPro.DataValueField = "provinceID"; this.ddlPro.DataBind(); this.ddlPro.Items.Insert(0, new ListItem("请选择","0")); } //选择省份后显示市区下拉框,并加载当前省份下的市区数据 protected void ddlPro_SelectedIndexChanged(object sender, EventArgs e) { ddlCity.Attributes.CssStyle.Add("display", "inline"); int proId = int.Parse(ddlPro.SelectedValue.ToString()); ViewState["proId"] = proId; BindCity(proId); } //绑定市区数据 private void BindCity(int proId) { string sql = @"SELECT [id] ,[cityID] ,[city] ,[father] FROM [Public].[dbo].[City] where [email protected]"; SqlParameter[] paras ={ new SqlParameter("@proId",proId) }; DataTable dt = db.GetDataTable(sql, paras); this.ddlCity.DataSource = dt; this.ddlCity.DataTextField = "city"; this.ddlCity.DataValueField = "cityID"; this.ddlCity.DataBind(); this.ddlCity.Items.Insert(0, new ListItem("请选择", "0")); } //选择城市后显示地区下拉框,并加载当前城市下的地区数据 protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e) { ddlArea.Attributes.CssStyle.Add("display", "inline"); int cityId = int.Parse(ddlCity.SelectedValue.ToString()); BindArea(cityId); } //绑定地区数据 private void BindArea(int cityId) { string sql = @"SELECT [id] ,[areaID] ,[area] ,[father] FROM [Public].[dbo].[Area] where [email protected]"; SqlParameter[] paras ={ new SqlParameter("@cityId",cityId) }; DataTable dt = db.GetDataTable(sql, paras); this.ddlArea.DataSource = dt; this.ddlArea.DataTextField = "area"; this.ddlArea.DataValueField = "areaID"; this.ddlArea.DataBind(); this.ddlArea.Items.Insert(0, new ListItem("请选择", "0")); }
时间: 2024-09-28 23:37:01