Home >Database >Mysql Tutorial >MVC4.0搭建的省市县三联动,包含数据库

MVC4.0搭建的省市县三联动,包含数据库

WBOY
WBOYOriginal
2016-06-07 15:47:181191browse

才学的MVC哈。 最近有个需要,从数据库读取省市县表的数据,通过MVC4搭建的程序展现出来,网上找了很多资料,都没一个全的,能用的,就自己动手。 一、建立MVC项目:City 二、创建数据模型 CityModel 三个表:T_Province 省份,T_City 城市,T_District 区县

才学的MVC哈。

最近有个需要,从数据库读取省市县表的数据,通过MVC4搭建的程序展现出来,网上找了很多资料,都没一个全的,能用的,就自己动手。


一、建立MVC项目:City

二、创建数据模型

CityModel

三个表: T_Province 省份,T_City 城市,T_District 区县

USE [liandong]
GO
/****** Object:  Table [dbo].[T_Province]   ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[T_Province](
	[ProID] [int] NOT NULL,
	[ProName] [nvarchar](50) NOT NULL,
	[ProSort] [int] NULL,
	[ProRemark] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[T_District]   ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[T_District](
	[Id] [int] NOT NULL,
	[DisName] [nvarchar](30) NOT NULL,
	[CityID] [int] NOT NULL,
	[DisSort] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[T_City]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[T_City](
	[CityID] [int] NOT NULL,
	[CityName] [nvarchar](50) NOT NULL,
	[ProID] [int] NULL,
	[CitySort] [int] NULL
) ON [PRIMARY]
GO


后面提供省市县的城市数据数据.SQL。

三、建立控制器

CityController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using City.Models;

namespace City.Controllers
{
    public class CityController : Controller
    {
        //
        // GET: /City/
        DBEntities db = new DBEntities();//数据链接
        public ActionResult Index() //前台展示的页面
        {
            return View();


        }
        /// <summary>
        /// 获取省份
        /// </summary>
        public JsonResult GetProvincelist()
        {

            IQueryable<t_province> queryResult = db.T_Province;//获取省份T_Province表的数据
            return Json(queryResult.ToList(), JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 获取城市
        /// </summary>
        /// <param name="pid">
        /// <returns></returns>
        public JsonResult GetCitylist(int pid)//根据省份ID获取城市
        {
            List<city.models.t_city> list = db.T_City.Where(c => c.ProID == pid).ToList();//城市ID对应值
            List<selectlistitem> item = new List<selectlistitem>();//获取城市列表
            foreach (var City in list)//根据列表获取城市名称和ID
            {
                item.Add(new SelectListItem { Text = City.CityName, Value = City.CityID.ToString() });
            }
            return Json(item, JsonRequestBehavior.AllowGet);

        }

        public JsonResult GetDistrictlist(int cid)//根据城市ID获取区县ID
        {

            List<city.models.t_district> list = db.T_District.Where(a => a.CityID == cid).ToList();//区县ID对应值
            List<selectlistitem> item = new List<selectlistitem>();//获取区县列表
            foreach (var District in list)//根据列表获取区县名称和ID
            {
                item.Add(new SelectListItem { Text = District.DisName, Value = District.Id.ToString() });
            }
            return Json(item, JsonRequestBehavior.AllowGet);
        }
    }
}
</selectlistitem></selectlistitem></city.models.t_district></selectlistitem></selectlistitem></city.models.t_city></t_province>


四、建立路由

RouteConfig

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace City
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "City", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

五、项目增加jquery-1.7.2.min.js引用。


六、建立前台Views,文件夹:City;文件名:Index


@{
    ViewBag.Title = "Index";
}
<script src="/javascript/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
 
    $(document).ready(function () {
        GetProvince();//加载省份
        $("#T_Province").change(function () { GetCity() });//加载城市
        $("#T_City").change(function () { GetDistrict() });//加载区县
    });
    function GetProvince() {
        $("#T_Province").empty();//清空省份SELECT控件
        $.getJSON("/City/GetProvincelist", function (data) {                
                $.each(data, function (i, item) {
                    $("<option>").val(item["ProID"]).text(item["ProName"]).appendTo($("#T_Province"));
                })
                GetCity();
            });
          
    }    


        function GetCity() {
            $("#T_City").empty();//清空城市SELECT控件
            $.getJSON(
            "/City/GetCitylist",
            { pid: $("#T_Province").val() },
            function (data) {
                $.each(data, function (i, item) {
                    $("<option>").val(item["Value"]).text(item["Text"]).appendTo($("#T_City"));
                    
                })
                GetDistrict();
            });           

        }
        function GetDistrict() {
            $("#T_District").empty();//清空区县SELECT控件
        $.getJSON(
            "/City/GetDistrictlist",
            {
                cid: $("#T_City").val()
            },
            function (data) {
                $.each(data, function (i, item) {
                    $("<option>").val(item["Value"]).text(item["Text"]).appendTo($("#T_District"));
                })
            });
        }
</script>

<span>省份</span>
<select id="T_Province">
    <option value="0">请选择</option>
</select>
<span>城市</span>
<select id="T_City">
    <option value="0">请选择</option>
</select><br>
<span>乡镇</span>
<select id="T_District">
    <option value="0">请选择</option>
</select>


省市区三级联动数据库Mssql:http://download.csdn.net/detail/qq_17202783/8415187


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:MySQL 外键约束Next article:MySQL 5.5.38安装出现的问题