地址連動功能,選擇縣市後在下一個DropDownList出現鄉鎮市區_ASP.NET
這個功能再平凡不過了,這篇文章用 Entity Framework 實作,請各位朋友多指教。
先看一下執行的畫面,一開始是上面兩個待選擇的 DropDownList,上圖因為還沒有選擇縣市,所以在鄉鎮市區的地方沒有顯示出來,下圖則是已選擇縣市為台北市,右方就出現台北市所屬的分區。
資料庫有兩張表,分別是 City 和 Country
資料表:City | 資料表:Country |
程式功能很簡單,選擇縣市之後右方的 DropDownList 會出現所屬鄉鎮市
畫面程式碼
<form id="form1" runat="server"> <div> 縣市:<asp:DropDownList ID="ddlCity" runat="server" AutoPostBack="True" onselectedindexchanged="ddlCity_SelectedIndexChanged"> </asp:DropDownList> 鄉鎮市區:<asp:DropDownList ID="ddlCountry" runat="server"> </asp:DropDownList> </div> </form>
程式碼
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bindCity(); setDDLDefault(); } } /// <summary> /// 繫結縣市 /// </summary> private void bindCity() { MyTestDBEntities entity = new MyTestDBEntities(); var city = from c in entity.City select new { cityID = c.cityID, cityName = c.cityName }; ddlCity.DataSource = city; ddlCity.DataTextField = "cityName"; ddlCity.DataValueField = "cityID"; ddlCity.DataBind(); } /// <summary> /// 用縣市ID繫結鄉鎮市區 /// </summary> private void bindCountry() { MyTestDBEntities entity = new MyTestDBEntities(); int cityID = Int32.Parse(ddlCity.SelectedValue); var country = from c in entity.Country where c.cityID == cityID select new { countryID = c.countryID, countryName = c.countryName }; ddlCountry.DataSource = country; ddlCountry.DataTextField = "countryName"; ddlCountry.DataValueField = "countryID"; ddlCountry.DataBind(); } /// <summary> /// 將兩個 DropDownList 的預設第一個選項都設定為「請選擇」 /// </summary> private void setDDLDefault() { ddlCity.Items.Insert(0, new ListItem("請選擇", "-1")); ddlCountry.Items.Insert(0, new ListItem("請選擇", "-1")); } /// <summary> /// 選擇了縣市後帶出鄉鎮市區 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e) { if (ddlCity.SelectedValue != "-1") { bindCountry(); } else { ddlCountry.Items.Clear(); ddlCountry.Items.Insert(0, new ListItem("請選擇", "-1")); } }