本文介紹使用jQuery的AJAX功能和asp.net來實作省市區的三級關聯效果,其他二級、三級或多級關聯也可以按照此方法完成。
文章中涉及到的資料表為City,為友善管理。
設計此表如下
ID:自增長字段
City_Name:城市名稱
City_Code:城市代碼
我們根據城市代碼來查詢省、市、區。城市代碼結構大緻如下:
内蒙古:150000,呼和浩特:150100,新城區:150101。
其他地區代碼與此一樣,省級為省級編号+0000,市級為省級編号+市級編号+00,地區為省級編号+市級編号+地區編号。
City.ASPX代碼為:
jQuery + ASP.NET實作三級關聯
#dpCity{ display:none; position:relative;}
#dpArea{ display:none;position:relative;}
省:
市:
區:
JS代碼:
jQuery(document).ready(function () {
var dp1 = jQuery("#dpProvince");
var dp2 = jQuery("#dpCity");
var dp3 = jQuery("#dpArea");
//填充省的資料
loadAreas("", "dpProvince");
//給省綁定事件,觸發事件後填充市的資料
jQuery(dp1).bind("change keyup", function () {
var provinceID = dp1.attr("value");
loadAreas(provinceID, "dpCity");
dp2.fadeIn("slow");
});
//給市綁定事件,觸發事件後填充區的資料
jQuery(dp2).bind("change keyup", function () {
var cityID = dp2.attr("value");
loadAreas(cityID, "dpArea");
dp3.fadeIn("slow");
});
});
function loadAreas(val, item) {
jQuery.ajax({
type: "post",
url: "CityLoader.asmx/GetCityList",
data: {
code: val,
a: Math.random()
},
error: function () {
return false;
},
success: function (data) {
var i;
var json = eval(data);
jQuery("#" + item).append("請選擇");
for (i = 0; i < json.length; i++) {
jQuery("#" + item).append(jQuery("").val(json[i].c_code).html(json[i].c_name));
};
}
});
}
背景代碼:
//執行個體類
public class CityModel
{
int _id;
string _cityname;
string _citycode;
public int ID
{
set { _id = value; }
get { return _id; }
}
public string CityName
{
set { _cityname = value; }
get { return _cityname; }
}
public string CityCode
{
set { _citycode = value; }
get { return _citycode; }
}
}
//DAL層,傳回DataTable,使用通用SqlHelper
public DataTable CityList(string pcode)
{
string SQL = "SELECT * FROM city WHERE 1=1";
if (!string.IsNullOrEmpty(pcode))
{
if (pcode.Substring(2, 2) != "00")
{
SQL = SQL + " AND RIGHT(citycode,2)<>'00' AND LEFT(citycode,4)=LEFT(@pcode,4)";
}
else
{
SQL = SQL + " AND RIGHT(citycode,2)='00' AND LEFT(RIGHT(citycode,4),2)<>'00' AND LEFT(citycode,2)=LEFT(@pcode,2)";
}
}
else
{
SQL = SQL + " AND LEFT(citycode,2)<>'00' AND RIGHT(citycode,4)='0000'";
}
SQL = SQL + " ORDER BY sorts ASC";
SqlParameter[] Param ={
new SqlParameter("@pcode",pcode)
};
using (SqlConnection conn = new SqlConnection(DBUtility.SqlHelper.ConnectionStringLocalTransaction))
{
DataSet ds = DBUtility.SqlHelper.ExecuteDataSet(conn, CommandType.Text, SQL, Param);
return ds.Tables[0];
}
}
//BLL層,傳回City的泛型清單
public List CityList(string code)
{
List list = new List();
DAL. CityDAL cd = new DAL.CityDAL();
DataTable dt = cd.CityList(code);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
CityModel cm = new CityModel();
cm.ID = int.Parse(dt.Rows[i]["id"].ToString());
cm.CityName = dt.Rows[i]["cityname"].ToString();
cm.CityCode = dt.Rows[i]["citycode"].ToString();
list.Add(cm);
}
}
return list;
}
CityLoader.asmx:
///
/// CityLoader 的摘要說明
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的注釋。
// [System.Web.Script.Services.ScriptService]
public class CityLoader : System.Web.Services.WebService
{
[WebMethod]
public void GetCityList(string code)
{
CityBLL cb = new CityBLL();
StringBuilder sb = new StringBuilder();
List cm = cb.CityList(code);
sb.Append("[");
if (cm.Count > 0)
{
for (int i = 0; i < cm.Count; i++)
{
CityModel model = cm[i];
sb.Append("{");
sb.AppendFormat(@"""c_name"":""{0}"",", model.CityName);
sb.AppendFormat(@"""c_code"":""{0}""", model.CityCode);
sb.Append("}");
if (i < cm.Count - 1)
{
sb.Append(",");
}
}
}
sb.Append("]");
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
System.Web.HttpContext.Current.Response.Write(sb.ToString());
}
}