jquery 实现二级/三级/多级联动菜单的思路及代码
本文介绍使用jquery的ajax功能和.net来实现省市区的三级联动效果,其他二级、三级或多级联动也可以按照此方法完成。
文章中涉及到的数据表为city,为方便管理。
设计此表如下
id:自增长字段
city_name:城市名称
city_code:城市代码
我们根据城市代码来查询省、市、区。城市代码结构大致如下:
内蒙古:150000,呼和浩特:150100,新城区:150101。
其他地区代码与此一样,省级为省级编号+0000,市级为省级编号+市级编号+00,地区为省级编号+市级编号+地区编号。
city.aspx代码为:
. 代码如下:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>jquery + asp.net实现三级联动</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>
<p>
省:<asp:dropdownlist id="dpprovince" runat="server"></asp:dropdownlist>
市:<asp:dropdownlist id="dpcity" runat="server"></asp:dropdownlist>
区:<asp:dropdownlist id="dparea" runat="server"></asp:dropdownlist>
</p>
</body>
</html>
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("<option value='' selected='selected'>请选择</option>");
for (i = 0; i < json.length; i++) {
jquery("#" + item).append(jquery("<option></option>").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<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 = "https://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());
}
}
上一篇: 挽回出轨老公最佳时间是什么时候?
下一篇: JSP代码 MVC编程开发实例