省市信息存储在tblArea表中,AreaPid等于0表示省一级名称,若要找省一级信息,则select * from tblArea areaPid=0 ;若找安徽省的县市则select * from tblArea where areapid=13
首先建立tblArea的EF类,然后建立Controllers
- using C02MVC.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace C02MVC.Controllers
- {
- public class HomeController : Controller
- {
- //
- // GET: /Home/
- nononodeleteImportantEntities1 data = new nononodeleteImportantEntities1();
- public ActionResult Index()
- {
- List<TblArea> list = data.TblArea.Where(model => model.AreaPId == 0).ToList();
- return View(list);
- }
- public ActionResult GetCity(int id)
- {
- List<TblArea> list =data.TblArea.Where(model => model.AreaPId == id).ToList();
- return PartialView(list);
- }
- }
- }
建立index视图,用来显示省份及相应的县市
- @{
- Layout = null;
- }
- @model List<C02MVC.Models.TblArea>
- <!DOCTYPE html>
- <html>
- <head>
- <script src="~/Scripts/jquery-1.7.1.js"></script>
- <script src="~/Scripts/jquery.validate.js"></script>
- <Meta name="viewport" content="width=device-width" />
- <title>Index</title>
- <script type="text/javascript">
- $(function () {
- var province = $("#province");
- $("#city").load("/home/GetCity/" + province.val());
- province.change(function () {
- $("#city").load("/home/GetCity/" + province.val());
- });
- });
- </script>
- </head>
- <body>
- <div>
- <select id="province">
- @foreach (var item in Model)
- {
- <option value="@item.AreaId">
- @item.AreaName
- </option>
- }
- </select>
- <select id="city">
- </select>
- </div>
- </body>
- </html>
建立GetCity视图,为Ajax方式获取市县提供数据
- @{
- Layout = null;
- }
- @model List<C02MVC.Models.TblArea>
- @foreach(var m in Model)
- {
- <option value="@m.AreaId">@m.AreaName</option>
- }