欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

基于MVC3方式实现下拉列表联动(JQuery)_jquery

程序员文章站 2022-05-10 14:45:21
...
上次项目中遇到一个需要多个下拉列表联动的操作,今天有空将实现方式整理以便以后参考。
要达到的效果是,点击一个下拉框,则另一个下拉框的值发生对应变化。如:选择中国,则另个一下拉框里显示中国各个省份。
传统的HTML方式比较简单,实际上基于MVC的实现方式也大同小异。

直接上代码:
复制代码 代码如下:

public class DP_Provice
{
public int proviceID { get; set; }
public string ProviceName { get; set; }
public int ProviceNode { get; set; }
public virtual List citySource { get; set; }
}

public class DP_City
{
public int CityNode { get; set; }
public string CityName { get; set; }
public string ProviceNode { get; set; }
}

对以上涉及到的实体类予以赋值,暂时使用一个静态类初始化简单数据:
复制代码 代码如下:

public static class DPDataSource
{
public static List InitalData()
{
List source = new List
{
new DP_Provice{ ProviceNode=1, ProviceName="北京", citySource=new List{
new DP_City{
CityNode=11, CityName="北京海淀"
},
new DP_City{
CityNode=12,CityName="北京西城"
}
}},
new DP_Provice{ ProviceNode=2, ProviceName="山东", citySource=new List{
new DP_City{
CityNode=21, CityName="济南"
},
new DP_City{
CityNode=22,CityName="德州"
}
}},
new DP_Provice{ ProviceNode=3, ProviceName="河北", citySource=new List{
new DP_City{
CityNode=31, CityName="石家庄"
},
new DP_City{
CityNode=32,CityName="衡水"
}
}}
};

return source;
}
}

具体在Controller中的调用,因为使用的JQuery中的AJAX方式,所以返回的结果类型为Json;
复制代码 代码如下:

public ActionResult Index()
{
return View("DPShow");
}
List source = DPDataSource.InitalData();

public JsonResult GetProvinceSource()
{
if (source == null || source.Count {
source = DPDataSource.InitalData();
}
return Json(source, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCitySource(string proviceName)
{
source = DPDataSource.InitalData();
List citySource = new List();
citySource = source.Where(a => a.ProviceNode.ToString().Contains(proviceName)).First().citySource;
return Json(citySource, JsonRequestBehavior.AllowGet);
}

数据准备完毕,此时需要Razor视图中进行绑定和展示,代码如下:
复制代码 代码如下:

@model MvcApplication.Models.DP_Provice
@{
ViewBag.Title = "DPShow";
Layout = "~/Views/Shared/_Layout.cshtml";
}



下拉列表联动













说明:
一般来讲,采用MVC实现下拉列表绑定可以有多种方式,主要是数据绑定方式可以使用JQuery中的Ajax 方式,同时也可以使用自定义的基于MVC 的 Url.Acion 方式,个人建议使用基于MVC 的 Url.Acion。
一来是支持方式比较灵活,如果中间涉及到数据类型复杂,可以自定义,实现数据封装;
二来是JQuery 中URL在传递参数时需要格式化,否则将无法找到指定的Action。
如有大家对上述说法有异议或者更好的实现方案,请给予指正或说明,谢谢。