本文记录了一个在MVC4中使用PartialView实现级联效果的小例子。
准备工作
首先准备一下要级联的数据,新建两个类:Province和City
public class Province
{
public string Id { get; set; } public string Name { get; set; }
} public class City
{
public string Id { get; set; } public string Name { get; set; } public string Province { get; set; }
}
并在Controller中准备好数据,
List<Province> provinceList = new List<Province>();
List<City> cityList = new List<City>(); private void InitData()
{
provinceList.Add(new Province { Id = "", Name = "河北省" });
provinceList.Add(new Province { Id = "", Name = "河南省" });
provinceList.Add(new Province { Id = "", Name = "广东省" }); cityList.Add(new City { Id = "", Name = "石家庄", Province = "" });
cityList.Add(new City { Id = "", Name = "邢台", Province = "" });
cityList.Add(new City { Id = "", Name = "保定", Province = "" }); cityList.Add(new City { Id = "", Name = "郑州", Province = "" });
cityList.Add(new City { Id = "", Name = "安阳", Province = "" });
cityList.Add(new City { Id = "", Name = "洛阳", Province = "" }); cityList.Add(new City { Id = "", Name = "广州", Province = "" });
cityList.Add(new City { Id = "", Name = "中山", Province = "" });
cityList.Add(new City { Id = "", Name = "佛山", Province = "" });
}
Controller
在控制器中创建一个返回分步视图的Action,在前台第一级调用的时候触发这个action,返回第二级需要的数据。
public ActionResult ShowCity(string provinceId)
{
InitData();
var result = cityList.Where(city => city.Province == provinceId);
ViewBag.City = result;
return PartialView("PartialCity");
}
View
先创建一个PartialView:PartialCity.cshtml,如下:
@{
ViewBag.Title = "PartialCity";
} 城市: @Html.DropDownList("city_dropdownlist", new SelectList(ViewBag.City, "Id", "Name"))
在主View中的使用这个PartialView,
<div id="province">
省份: @Html.DropDownList("province_dropdownlist", new SelectList(ViewBag.Province, "Id", "Name"))
</div>
<div id="city">
@Html.Partial("PartialCity")
</div>
最后,需要在主View页面写几行js代码,给第一级dropdownlist注册一个change事件,并且在事件触发的时候调用刚刚创建的ShowCity方法
@Scripts.Render("~/Scripts/jquery-1.7.1.min.js");
<script type="text/javascript">
$(document).ready(init); function init() {
$("select[name='province_dropdownlist']").change(function () {
var selectedProvince = $(this).val();
ShowCityWithSelectedProvince(selectedProvince);
});
} function ShowCityWithSelectedProvince(province) {
$.ajax({
url: "@Url.Action("ShowCity", "Home")",
data: { provinceId: province },
success: function (data) {
$("#city").html(data);
}
});
}
这样,就实现了级联效果。
以上