1、Control层
/// <summary> /// action方法根据省份编号返回json形式的城市信息 /// </summary> /// <param name="p">省份编号</param> /// <returns></returns> public ActionResult GetCityList(string p) { ; IList<City> cityModelList =//根据省份编号返回城市信息 var pList = new SelectList(cityModelList, "CityId", "CityName"); return Json(pList, JsonRequestBehavior.AllowGet); } //绑定省份信息 public void BindProvince(string defaultText = "请选择", string defaultValue = "") { var dt =// 省份信息 IList<SelectListItem> items = new List<SelectListItem>(); items.Add(new SelectListItem { Text = defaultText, Value = "", Selected = true }); foreach (var dr in dt) { items.Add(new SelectListItem { Text = dr.ProvinceName, Value = dr.ProvinceCode }); } this.controller.ViewData["Province"] = items; this.controller.ViewData["ddlProvince"] = defaultValue ?? string.Empty; } //绑定省市信息 public void BindCity(string provinceId, string defaultText = "请选择", string defaultValue = "") { IList<SelectListItem> items = new List<SelectListItem>(); if (provinceId == string.Empty) { items.Add(new SelectListItem { Text = defaultText, Value = defaultValue }); } else { var dt = //根据省份编号获取城市信息 foreach (var dr in dt) { items.Add(new SelectListItem { Text = dr.CityName, Value = dr.CityId }); } } this.controller.ViewData["City"] = items; this.controller.ViewData["ddlCity"] = defaultValue ?? string.Empty; }
2、View层<script src="@Url.Content("~/Scripts/provinceCity.js")" type="text/javascript"></script> <div class="editor-label"> 省份城市 </div> <div> @Html.DropDownList("ddlProvince", ViewData["Province"] as IEnumerable<SelectListItem>) @Html.DropDownList("ddlCity", ViewData["City"] as IEnumerable<SelectListItem>) @Html.ValidationMessageFor(model => model.CityId) </div> //隐藏字段用于在js调用,设置url路径 @Html.Hidden("GetCityList", Url.Action("GetCityList", "Enterprise"))3、Js代码$(document).ready(function () {
$("#ddlProvince").change(function () { getCity($(this).val()); });
function getCity(provinveCode) {
$("#ddlCity").html(""); //清空
$.ajax({
type: "GET",
url: $("#GetCityList").val(),
data: "p=" + provinveCode + "&date=" + new Date(),
dataType: "json",
success: function (json) {
if (json.length > 0) {
for (var i = 0; i < json.length; i++) {
$("#ddlCity").append("<option value='" + json[i].Value + "'>" + json[i].Text + "</option>");
}
} else {
$("#ddlCity").append("<option value=''>请选择</option>");
}
},
error: function (data) {
alert(data);
}
});
}
});