数据表为City,为方便管理。
设计此表:
ID:自增长字段
City_Name:城市名称
City_Code:城市代码
我们根据城市代码来查询省、市、区。城市代码结构大致如下:
内蒙古:150000,呼和浩特:150100,新城区:150101。
其他地区代码与此一样,省级为省级编号+0000,市级为省级编号+市级编号+00,地区为省级编号+市级编号+地区编号。
City.ASPX代码:
JS代码:
后台代码:
//实例类
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<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:
/// <summary>
/// CityLoader 的摘要说明
/// </summary>
[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<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());
}
}