在mvc中用ajax实现省市联动

前端之家收集整理的这篇文章主要介绍了在mvc中用ajax实现省市联动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

省市信息存储在tblArea表中,AreaPid等于0表示省一级名称,若要找省一级信息,则select * from tblArea areaPid=0 ;若找安徽省的县市则select * from tblArea where areapid=13



首先建立tblArea的EF类,然后建立Controllers


  1. using C02MVC.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7.  
  8. namespace C02MVC.Controllers
  9. {
  10. public class HomeController : Controller
  11. {
  12. //
  13. // GET: /Home/
  14. nononodeleteImportantEntities1 data = new nononodeleteImportantEntities1();
  15. public ActionResult Index()
  16. {
  17. List<TblArea> list = data.TblArea.Where(model => model.AreaPId == 0).ToList();
  18. return View(list);
  19. }
  20. public ActionResult GetCity(int id)
  21. {
  22. List<TblArea> list =data.TblArea.Where(model => model.AreaPId == id).ToList();
  23. return PartialView(list);
  24. }
  25. }
  26. }


建立index视图,用来显示省份及相应的县市

  1. @{
  2. Layout = null;
  3. }
  4. @model List<C02MVC.Models.TblArea>
  5. <!DOCTYPE html>
  6.  
  7. <html>
  8. <head>
  9. <script src="~/Scripts/jquery-1.7.1.js"></script>
  10. <script src="~/Scripts/jquery.validate.js"></script>
  11. <Meta name="viewport" content="width=device-width" />
  12. <title>Index</title>
  13. <script type="text/javascript">
  14. $(function () {
  15. var province = $("#province");
  16. $("#city").load("/home/GetCity/" + province.val());
  17. province.change(function () {
  18. $("#city").load("/home/GetCity/" + province.val());
  19. });
  20. });
  21. </script>
  22. </head>
  23. <body>
  24. <div>
  25. <select id="province">
  26.  
  27. @foreach (var item in Model)
  28. {
  29. <option value="@item.AreaId">
  30. @item.AreaName
  31. </option>
  32. }
  33. </select>
  34. <select id="city">
  35.  
  36. </select>
  37. </div>
  38. </body>
  39. </html>


建立GetCity视图,为Ajax方式获取市县提供数据

  1. @{
  2. Layout = null;
  3. }
  4. @model List<C02MVC.Models.TblArea>
  5.  
  6. @foreach(var m in Model)
  7. {
  8. <option value="@m.AreaId">@m.AreaName</option>
  9. }






猜你在找的Ajax相关文章