后台代码,获取数据如下:
View Code
1 /// <summary> 2 /// 获取省份 3 /// </summary> 4 public JsonResult GetProvincelist() 5 { 6 return Json(db.Province.ToList(),JsonRequestBehavior.AllowGet); 7 } 8 /// <summary> 9 /// 获取城市 10 /// </summary> 11 /// <param name="pid"></param> 12 /// <returns></returns> 13 public JsonResult GetCitylist(int pid) 14 { 15 List<CityModel> list=db.City.Where(c => c.Province.PID == pid).ToList(); 16 List<SelectListItem> item = new List<SelectListItem>(); 17 foreach (var City in list) 18 { 19 item.Add(new SelectListItem { Text = City.CityName, Value = City.CID.ToString() }); 20 } 21 return Json(item, JsonRequestBehavior.AllowGet); 22 }
定义两个下拉框:
View Code
1 <span>省份:</span> 2 <select id="Province" > 3 <option>请选择</option> 4 </select> 5 6 <span>市:</span> 7 <select id="City"> 8 <option>请选择</option> 9 </select>
使用jquery获取控制器里返回的值加载到下拉框中:
View Code
1 <script type="text/javascript"> 2 $(function () { 3 GetProvince(); //加载省份 4 $("#Province").change(function () { 5 GetCity(); 6 }); 7 }); 8 function GetProvince() { 9 // $("#Province").empty(); 10 $.getJSON( 11 "/Home/GetProvincelist", 12 function (data) { 13 alert(data); 14 $.each(data, function (i, item) { 15 $("<option></option>").val(item["PID"]).text(item["ProvinceName"]).appendTo($("#Province")); 16 }) 17 }); 18 // GetCity(); 19 } 20 function GetCity() { 21 $("#City").empty(); 22 $.getJSON( 23 "/Home/GetCitylist", 24 { pid: $("#Province").val() }, 25 function (data) { 26 $.each(data, function (i, item) { 27 $("<option></option>").val(item["Value"]).text(item["Text"]).appendTo($("#City")); 28 29 }) 30 }); 31 } 32 </script>