您的位置:首页 > 编程语言

MVC 对中国省市区的联动查询代码。

2015-07-11 13:56 465 查看
Model里的代码

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

namespace Mvcshengshiqu.Models
{
public class ChinaBF
{
private masterDataContext _Context = new masterDataContext();
public List<ChinaStates> Select()
{
return _Context.ChinaStates.ToList();
}
//因为所有的数据都在一个表里,所以通过编号查询身份,通过省份查询城市,或者通过城市查询地区
public List<ChinaStates> Selectcity(string Areacode)
{
var query = _Context.ChinaStates.Where(p=>p.ParentAreaCode==Areacode);
if (query.Count()>0)
{
return query.ToList();
}
return null;
}
}
}


控制器里的代码

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

namespace Mvcshengshiqu.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
[HttpGet]
public ActionResult Index()
{

string ParentAreaCode = "0001";
//通过编号001查询出的就是所有的省份
List<ChinaStates> list = new ChinaBF().Selectcity(ParentAreaCode);
ViewBag.Data1 = new SelectList(list,"AreaCode","AreaName");

//默认显示北京
string Areacode = "11";
List<ChinaStates> list1 = new ChinaBF().Selectcity(Areacode);
ViewBag.Data2 = new SelectList(list1,"AreaCode","AreaName");

//默认显示北京的辖区

string Areacode1 = "1101";
List<ChinaStates> list2 = new ChinaBF().Selectcity(Areacode1);
ViewBag.Data3 = new SelectList(list2,"AreaCode","AreaName");

return View();
}

[HttpPost]
//当页面提交时,就会改变数据,联动显示
public ActionResult Index(string sheng,string shi,string qu)
{
string ParentAreaCode = "0001";
//通过编号0001把所有的省份查询出来
List<ChinaStates> list = new ChinaBF().Selectcity(ParentAreaCode);
//第四个值是选定的省,通过选定的省来改变市
ViewBag.Data1 = new SelectList(list, "AreaCode", "AreaName",sheng);

//第四个值是选定的市,通过选定的市来改变区
List<ChinaStates> list1 = new ChinaBF().Selectcity(sheng);
ViewBag.Data2 = new SelectList(list1, "AreaCode", "AreaName",shi);

//判断一下市是不是当前的市。如果改一下省,市会改变,根据市改变区
var b=list1.Exists(p=>p.AreaCode==shi)?shi:list1[0].AreaCode;

//通过选定的市改变区
List<ChinaStates> listcity = new ChinaBF().Selectcity(b);
ViewBag.Data3 = new SelectList(listcity, "AreaCode", "AreaName");

return View();
}
}
}


视图里的代码

@using Mvcshengshiqu.Controllers;
@using  Mvcshengshiqu.Models;
@model List<ChinaStates>
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
SelectList aa = ViewBag.Data1;
SelectList bb = ViewBag.Data2;
SelectList cc = ViewBag.Data3;
}

@using(Html.BeginForm("Index","Home",FormMethod.Post))
{
<div>
省:@Html.DropDownList("sheng", aa, new {onchange="document.forms[0].submit();" })
市:@Html.DropDownList("shi", bb, new { onchange="document.forms[0].submit();"})
区:@Html.DropDownList("qu",cc)
</div>
}

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: