asp.net mvc jQuery 城市二级联动

页面效果图:

asp.net mvc jQuery 城市二级联动

数据库表结构:

首先在数据库中创建省级、城市的表,我的表如下:我用了一张表放下了省级、城市的数据,用level划分省份和城市,parentId表示该城市所在省份的id

asp.net mvc jQuery 城市二级联动asp.net mvc jQuery 城市二级联动

主要文件有:index.cshtml,ErJLDController.cs ,数据处理层,业务处理层,还有数据库文件 。

index.cshtml:

 <body>
<div>
<select id="provinceId" >
<option> 请选择省份</option>
</select>
<select id="cityId">
<option>请选择市区</option>
</select>
</div> <script type="text/javascript"> //用json从数据库里取一级列表的参数
$(function () { $.getJSON("ErJLD/getProvince/", function (obj) {
$.each(obj, function (i, p) {
$("#provinceId").append("<option value='"+p.id+"'>" + p.areaValue + "</option>");
}); $("#provinceId").change(function () {
//用attr()方法获取当前选择的option的value值(即p.id ,数据库里的id值,
//虽然在TestController中的getCity方法中传入的是string类型的形参,但是后来需要变换成int类型, 所以value值应该为数字)
var pName = $("#provinceId").attr("value");
$.getJSON("ErJLD/getCity?pName=" + pName, getcity);
});
});
}); function getcity(obj) {
$("#cityId").empty();
$.each(obj, function (m, v) {
$("#cityId").append("<option >" + v.areaValue + "</option>");
}); }; </script>
</body> Index.cshtml

ErJLDController.cs

 namespace Mvcproject.Controllers
{
//二级联动
public class ErJLDController : Controller
{ ZjbEntities db = new ZjbEntities();
//
// GET: /Test/ public ActionResult Index()
{
//pro_city province=new pro_city(); return View();
} public JsonResult getProvince() { List<pro_city> provinceList = (from p in db.pro_city where p.level == select p).ToList(); JsonResult Jprovince = new JsonResult();
Jprovince.Data = provinceList;
Jprovince.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return Jprovince; } public JsonResult getCity(string pName)
{ //string pid = (from p in db.pro_city where p.areaValue == pName select p.id).ToString();
//int id = int.Parse(pid);
int id = int.Parse(pName); List<pro_city> cityList = (from p in db.pro_city where p.parentId == id select p).ToList(); JsonResult Jcity = new JsonResult();
Jcity.Data = cityList;
Jcity.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return Jcity; } }
} ErJLDController.cs
上一篇:Swagger中展示的请求参数错误问题


下一篇:noip模拟65[第一次在知道难度的情况下做题]