前台代码:
<asp:DropDownList runat="server" ID="ddlProvince"></asp:DropDownList> <asp:DropDownList runat="server" ID="ddlCity"></asp:DropDownList>
后台绑定省份
protected void Page_Load(object sender, EventArgs e){ BindDDL(); ddlProvince.Attributes.Add("onchange", "getCitys(this)");}public void BindDDL(){//绑定省份、直辖市和特别行政区 ddlProvince.Items.Clear(); DataSet dsProvince = Province.GetAllCES(); ddlProvince.DataSource = dsProvince; ddlProvince.DataTextField = "ProvinceName"; ddlProvince.DataValueField = "ProvinceID"; ddlProvince.DataBind(); ddlProvince.Items.Add(new ListItem("其他", "0"));}
js事件处理getCitys(),为了提高性能,下面不该创建一个个的option对象然后一个个的添加到ddlcity里面,应该放到一个字符串里面然后一起放到optionddlcity里面,这里就不改了。
function getCitys(ddlProvince) { $.ajax({ url: "SettingsHandler.ashx", data: { type: "getCitys", ProvinceID: $(ddlProvince).find("option:selected").val() }, type: "get", cache: false, dataType: "json", error: function() { alert("occur error"); }, success: function(data) { $(‘#ddlCity‘).empty(); var option0 = $("<option></option>"); option0.text("不限"); option0.val("0"); $(‘#ddlCity‘).append(option0); if ($(ddlProvince).find("option:selected").val() != "0") { var objCitys = eval(data); $.each(objCitys.citys, function(i, city) { var option = $("<option></option>"); option.text(city.CityName); option.val(city.CityID); $(‘#ddlCity‘).append(option); }); } } }); }
SettingHandler.ashx文件
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string strjson = "{\"JDataList\":[]}"; string strType = context.Request.QueryString["type"].ToString(); if (strType == "getCitys")//根据省份ID获取对应的城市 { string strProvinceID = context.Request.Form["ProvinceID"].ToString(); DataSet dsCitys = Province.GetCitysByProvinceID(ValidateHelper.GetInt(strProvinceID)); if (DataHelper.DataIsNotNull(dsCitys)) { strjson = JsonHelper.DataTableToJSON(dsCitys.Tables[0], "citys"); } }
return strjson;}
JsonHelper.DataTableToJSON(DataTable dt,string dtName)方法:
public static string DataTableToJSON(DataTable dt, string dtName) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jw = new JsonTextWriter(sw)) { JsonSerializer ser = new JsonSerializer(); jw.WriteStartObject(); jw.WritePropertyName(dtName); jw.WriteStartArray(); foreach (DataRow dr in dt.Rows) { jw.WriteStartObject(); foreach (DataColumn dc in dt.Columns) { jw.WritePropertyName(dc.ColumnName); ser.Serialize(jw, dr[dc].ToString()); } jw.WriteEndObject(); } jw.WriteEndArray(); jw.WriteEndObject(); sw.Close(); jw.Close(); } return sb.ToString(); }
以上使用了JSON、JQUERY来实现省市的无刷新联动。
jquery 绑定省份和城市
时间: 2024-10-18 11:23:10