html:
<%=Html.DropDownList("num",Model) %>
<%=Html.DropDownList("items",new List<SelectListItem>{
(new SelectListItem(){Text="--請選擇--",Value="0",Selected=true})}) %>
其中,Model爲模型,是從Controller類中傳到html頁面的值,其數據類型是:IList<SelectListItem>
{
IList<Speciality> list = sp.FindSpecialities(); //獲得要綁定到下拉列表框的值
IList<SelectListItem> selectItem = new List<SelectListItem>();
selectItem.Add(new SelectListItem { Text = "--請選擇--", Value = 0 + "", Selected = true });//添加第一個下拉列表框的值
foreach (Speciality speciality in list)
{//循環添加下拉列表框的值
SelectListItem s = new SelectListItem { Text = speciality.SpcialityName, Value = speciality.ID + "", Selected = false };
selectItem.Add(s);
}
return View(selectItem);
}
jquery:
<script type="text/javascript" src="../../Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(function() {
$("#num").change(function() {
$.getJSON("../Test/GetSubject", { speID: $("#num").val() }, function(data) {
$("#items").empty();
$.each(data, function(i, item) {
$("<option></option>").val(item["Value"]).text(item["Text"]).appendTo($("#items"));
});
});
});
});
</script>
其中,引入了jquery 的jquery-1.3.2.js包,在第一個下拉列表框的值改變的時候(change)使用Ajax請求調用Controller類中的GetSubject方法,並對返回值進行處理。清空empty原先的值,然後循環添加返回的值到下拉列表框中。
Controller:
public JsonResult GetSubject(string speID)
{
int id = Convert.ToInt32(speID);
IList<Subject> subjects = sb.FindSubjectByState(id, 0);
List<SelectListItem> items = new List<SelectListItem>();
foreach (Subject item in subjects)
items.Add(new SelectListItem { Text = item.SubjectName, Value = item.ID+"" });
return Json(items);
}
返回值類型爲JsonResult,根據條件獲得值後添加到List<SelectListItem>集合中,並返回該值。