1、添加省份和城市类
//省份 public class Province { public int Id { get; set; } public string Name { get; set; } } //城市 public class City { public int Id { get; set; } public string Name { get;set;} public int ProvinceId { get; set; } }
2、添加控制器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SupermarketManagement.Models; namespace SupermarketManagement.Controllers { public class LinkageController : Controller { List<Province> provinceList = new List<Province>(); List<City> cityList = new List<City>(); //初始化城市数据 private void InitProvince() { provinceList.Add(new Province { Id = 1, Name = "河北省" }); provinceList.Add(new Province { Id = 2, Name = "河南省" }); provinceList.Add(new Province { Id = 3, Name = "广东省" }); cityList.Add(new City { Id = 4, Name = "石家庄", ProvinceId = 1 }); cityList.Add(new City { Id = 5, Name = "邢台", ProvinceId = 1 }); cityList.Add(new City { Id = 6, Name = "保定", ProvinceId = 1 }); cityList.Add(new City { Id = 7, Name = "郑州", ProvinceId = 2 }); cityList.Add(new City { Id = 8, Name = "安阳", ProvinceId = 2 }); cityList.Add(new City { Id = 9, Name = "洛阳", ProvinceId = 2 }); cityList.Add(new City { Id = 10, Name = "广州", ProvinceId = 3 }); cityList.Add(new City { Id = 11, Name = "中山", ProvinceId = 3 }); cityList.Add(new City { Id = 12, Name = "佛山", ProvinceId = 3 }); } //绑定省份 public ActionResult Index() { InitProvince(); var pEnumrable = provinceList.Select(p => new SelectListItem { Value = p.Id.ToString(), Text = p.Name }); ViewBag.Province = pEnumrable; return View(); } //获取城市 public ActionResult ShowCity(int provinceId) { InitProvince(); List<City> cList = new List<City>(); cList = cityList.Where(c => c.ProvinceId == provinceId).ToList(); return Json(cList, JsonRequestBehavior.AllowGet); } } }
3、添加HTML
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Content/jquery-1.8.3.min.js"></script> <script> $(function () { $("#Province").bind("change", function () { var selectProvince = $(this).val(); //除了第一个都删除 $("#City option:not(:first)").remove(); $.getJSON("@Url.Action("ShowCity","Linkage")", { provinceId: selectProvince }, function (data) { $.each(data, function (i, item) { $("#City").append("<option value='"+item.Id+"'>"+item.Name+"</option>"); }); }); }); }); </script> </head> <body> 省份:@Html.DropDownList("Province", "请选择省份")<br /> 城市:<select id="City"> <option value="">请选择城市</option> </select><br /> </body> </html>