加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在mvc中用ajax实现省市联动

发布时间:2020-12-16 00:37:37 所属栏目:百科 来源:网络整理
导读:省市信息存储在tblArea表中,AreaPid等于0表示省一级名称,若要找省一级信息,则select * from tblArea areaPid=0 ;若找安徽省的县市则select * from tblArea where areapid=13 首先建立tblArea的EF类,然后建立Controllers using C02MVC.Models;using Syste

省市信息存储在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>
}




??

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读