多级联动实现,附源码。当前,部分代码是参与博客园其它网友。
新增,前台代码:
省份:
市:
后台代码:
///
/// 模拟省份数据
///
///
public List Provincelist()
{
List list = new List();
list.Add(new Province() { PID = 1, ProvinceName = "广东" });
list.Add(new Province() { PID = 2, ProvinceName = "北京" });
list.Add(new Province() { PID = 3, ProvinceName = "上海" });
list.Add(new Province() { PID = 4, ProvinceName = "河北" });
list.Add(new Province() { PID = 5, ProvinceName = "贵州" });
list.Add(new Province() { PID = 6, ProvinceName = "云南" });
return list;
}
///
/// 模拟城市数据
///
///
public List Citylist()
{
List cityList = new List();
cityList.Add(new City() { CID = 1, PID = 1, CityName = "广州" });
cityList.Add(new City() { CID = 2, PID = 1, CityName = "深圳" });
cityList.Add(new City() { CID = 3, PID = 1, CityName = "惠州" });
cityList.Add(new City() { CID = 4, PID = 1, CityName = "湛江" });
cityList.Add(new City() { CID = 5, PID = 2, CityName = "北京" });
cityList.Add(new City() { CID = 6, PID = 3, CityName = "上海" });
cityList.Add(new City() { CID = 7, PID = 4, CityName = "唐山市" });
cityList.Add(new City() { CID = 8, PID = 4, CityName = "保定市" });
cityList.Add(new City() { CID = 9, PID = 4, CityName = "张家口市" });
return cityList;
}
///
/// 获取省份
///
public JsonResult GetProvincelist()
{
var list = Provincelist();
return Json(list, JsonRequestBehavior.AllowGet);
}
///
/// 获取城市
///
///
///
public JsonResult GetCitylist(int pid)
{
var citys = Citylist().Where(m => m.PID == pid).ToList();
List item = new List();
foreach (var City in citys)
{
item.Add(new SelectListItem { Text = City.CityName, Value = City.CID.ToString() });
}
return Json(item, JsonRequestBehavior.AllowGet);
}
编辑逻辑:
模型ProvinceViewModel:
public class ProvinceViewModel
{
///
/// 省份ID
///
public int PID { get; set; }
///
/// 城市ID
///
public int CID { get; set; }
}
前台:
省份:
@Html.DropDownListFor(model => model.PID, ViewBag.ProvinceList as IEnumerable, "=请选择=", new { @class = "form-control", id = "Province" })
市:
@Html.DropDownListFor(model => model.CID,ViewBag.CityList as IEnumerable, "=请选择=", new { @class = "form-control", id = "City" })
后台:
public ActionResult Edit()
{
ViewBag.ProvinceList = Provincelist().Select(m => new SelectListItem()
{
Text = m.ProvinceName,
Value = m.PID.ToString(),
Selected = (m.PID == 4) //测试,默认让它绑定第四个
}).ToList();
ViewBag.CityList = Citylist().Select(m => new SelectListItem()
{
Text = m.CityName,
Value = m.CID.ToString(),
Selected = (m.CID == 8) //测试,默认让它绑定第四个
}).ToList();
return View();
}
实际上,增加和编辑是完成可以合成同一个页面的,这里就不演示了。
源代码下载:点击下载