MVC 二级联动

后台代码,获取数据如下:

/// <summary>
/// 获取省份
/// </summary>
public JsonResult GetProvincelist()
{
return Json(db.Province.ToList(),JsonRequestBehavior.AllowGet);
}
/// <summary>
/// 获取城市
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
public JsonResult GetCitylist(int pid)
{
List<CityModel> list=db.City.Where(c => c.Province.PID == pid).ToList();
List<SelectListItem> item = new List<SelectListItem>();
foreach (var City in list)
{
item.Add(new SelectListItem { Text = City.CityName, Value = City.CID.ToString() });
}
return Json(item, JsonRequestBehavior.AllowGet);
}

定义两个下拉框:

<span>省份:</span>
<select id="Province" >
<option>请选择</option>
</select> <span>市:</span>
<select id="City">
<option>请选择</option>
</select>

使用jquery获取控制器里返回的值加载到下拉框中:

<script type="text/javascript">
$(function () {
GetProvince(); //加载省份
$("#Province").change(function () {
GetCity();
});
});
function GetProvince() {
// $("#Province").empty();
$.getJSON(
"/Home/GetProvincelist",
function (data) {
alert(data);
$.each(data, function (i, item) {
$("<option></option>").val(item["PID"]).text(item["ProvinceName"]).appendTo($("#Province"));
})
});
// GetCity();
}
function GetCity() {
$("#City").empty();
$.getJSON(
"/Home/GetCitylist",
{ pid: $("#Province").val() },
function (data) {
$.each(data, function (i, item) {
$("<option></option>").val(item["Value"]).text(item["Text"]).appendTo($("#City")); })
});
}
</script>

→原文链接←

上一篇:Go成功的项目


下一篇:mac的svn之cornerstone简易教程