This article describes how to use jQuery's AJAX function and asp.net to achieve the three-level linkage effect between provinces and municipalities. Other second-level, third-level, or multi-level linkages can also be completed according to this method.
The data table involved in this article is City, for convenient management.
Design this table as follows
ID: auto-increment Field
City_Name: city name
City_Code: city code
We can query the province, city, and District Based on the city code. The city code structure is roughly as follows:
Inner Mongolia: 150000, Hohhot: 150100, Xincheng District: 150101.
The code for other regions is the same as that for provincial numbers + 0000, municipal numbers + 00, and regional numbers + municipal numbers + regional numbers.
The City. ASPX code is:Copy codeThe Code is as follows: <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> jQuery + ASP. NET achieves three-level linkage </title>
<Script src = "/Scripts/jquery-1.4.1.min.js" type = "text/javascript"> </script>
<Style type = "text/css">
# DpCity {display: none; position: relative ;}
# DpArea {display: none; position: relative ;}
</Style>
</Head>
<Body>
<Div>
Province: <asp: DropDownList ID = "dpProvince" runat = "server"> </asp: DropDownList>
City: <asp: DropDownList ID = "dpCity" runat = "server"> </asp: DropDownList>
Area: <asp: DropDownList ID = "dpArea" runat = "server"> </asp: DropDownList>
</Div>
</Body>
</Html>
JS Code:Copy codeThe Code is as follows: jQuery (document). ready (function (){
Var dp1 = jQuery ("# dpProvince ");
Var dp2 = jQuery ("# dpCity ");
Var dp3 = jQuery ("# dpArea ");
// Fill in provincial data
LoadAreas ("", "dpProvince ");
// Bind the event to the province, and fill the city data after the event is triggered
JQuery (dp1). bind ("change keyup", function (){
Var provinceID = dp1.attr ("value ");
LoadAreas (provinceID, "dpCity ");
Dp2.fadeIn ("slow ");
});
// Bind an event to the city. Data in the filling area after the event is triggered
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 ("<option value = ''selected = 'selected'> select </option> ");
For (I = 0; I <json. length; I ++ ){
JQuery ("#" + item). append (jQuery ("<option> </option>" ).val(jsonpolici=.c_code=.html (json [I]. c_name ));
};
}
});
}
Background code:Copy codeThe Code is as follows: // instance class
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 ;}
}
}
// The DAL layer, which returns the DataTable and uses the General 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) = '123 '";
}
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];
}
}
// Return the generic list of the City at the BLL layer.
Public List <CityModel> CityList (string code)
{
List <CityModel> list = new List <CityModel> ();
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:Copy codeThe Code is as follows: // <summary>
/// Summary of CityLoader
/// </Summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
[System. ComponentModel. ToolboxItem (false)]
// To allow ASP. net ajax to call this Web service from a script, cancel the comments to the downstream.
// [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 <CityModel> 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 ());
}
}