public class HomeController : Controller { // // GET: /Home/ //默认显示的主页面 public ActionResult Index() { List<ChinaStates> listS = new ChinaStatesBF().SelectSheng(); SelectList listSheng = new SelectList(listS,"AreaCode","AreaName","0001"); List<ChinaStates> listC = new ChinaStatesBF().SelectCheng("11"); SelectList listCity = new SelectList(listC, "AreaCode", "AreaName"); ViewBag.Citys = listCity; List<ChinaStates> listD = new ChinaStatesBF().SelectDiQu("1101"); SelectList listDiQu = new SelectList(listD, "AreaCode", "AreaName"); ViewBag.DiQus = listDiQu; return View(listSheng); } [HttpPost] public ActionResult Index(string shengcode,string shicode,string diqucode) { try { //按提交的省编号定位省份 List<ChinaStates> listS = new ChinaStatesBF().SelectSheng(); SelectList listSheng = new SelectList(listS, "AreaCode", "AreaName", shengcode); //按省份查询城市 List<ChinaStates> listC = new ChinaStatesBF().SelectCheng(shengcode); SelectList listCity = new SelectList(listC, "AreaCode", "AreaName", shicode); ViewBag.Citys = listCity; //判断是否更改城市,来查询地区 var b = listC.Exists(p => p.AreaCode == shicode) ? shicode : listC[0].AreaCode; List<ChinaStates> listD = new ChinaStatesBF().SelectDiQu(b); SelectList listDiQu = new SelectList(listD, "AreaCode", "AreaName", diqucode); ViewBag.DiQus = listDiQu; return View(listSheng); } catch { return RedirectToAction("Index"); } } }
public class ChinaStatesBF { private MyDbDataContext Context = new MyDbDataContext(); //查询省 public List<ChinaStates> SelectSheng() { var q = Context.ChinaStates.Where(p => p.ParentAreaCode == "0001"); if (q.Count()>0) { return q.ToList(); } return null; } //查市 public List<ChinaStates> SelectCheng(string parentAreaCode) { var q = Context.ChinaStates.Where(p=>p.ParentAreaCode==parentAreaCode); if (q.Count()>0) { return q.ToList(); } return null; } //查地区 public List<ChinaStates> SelectDiQu(string parentAreaCode) { var q = Context.ChinaStates.Where(p => p.ParentAreaCode == parentAreaCode); if (q.Count() > 0) { return q.ToList(); } return null; } }
<div> @using (@Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.Label("text", "省份") @Html.DropDownList("shengcode", Model, new { onchange="document.forms[0].submit()" }) @Html.Label("text", "城市") @Html.DropDownList("shicode",ViewBag.Citys as SelectList, new { onchange="document.forms[0].submit()" }) @Html.Label("text", "地区") @Html.DropDownList("diqucode", ViewBag.DiQus as SelectList, new { onchange="document.forms[0].submit()" }) } </div>
效果