0
我想實現一個DropDownList多選擇使用Bootstrap Selectpicker在我的應用程序中選擇學校。Asp.Net Mvc Selectpicker
我對MVC和JQuery不是很熟悉,因爲我一直使用webforms很久,所以我正在從互聯網上學習來完成。
下面是這種情況:在我的佈局
,有一個DropDownList:
@*DropDownList Select School*@
@Html.DropDownList("Schools", null, null, new { id = "MultiSelect", @class = "selectpicker form-control", multiple = "", title = "School" })
的代碼來填充的DropDownList:
public ActionResult Class()
{
IEnumerable<SelectListItem> ListClasses = db.scasy_class
.OrderBy(a => a.class_name)
.Select(c => new SelectListItem
{
Value = c.id.ToString(),
Text = c.class_name,
Selected = false
});
ViewBag.Class = ListClasses.ToList();
ClassViewModel classViewModel = new ClassViewModel()
{
SelectOptions = ListClasses
};
return View(classViewModel);
}
在佈局,用戶選擇時一些學校使用下拉列表,
$('#MultiSelect').on('change', function() {
$.each($("#MultiSelect option"), function() {
$.post("/Setup/Student/SetSchool/", { school: $(this).val(), selected: $(this).prop('selected') });
});
});
和控制器;
public ActionResult SetSchool(int school, bool selected)
{
ArrayList school_nos = Session["Schools"] as ArrayList;
if (selected)
{
if (!school_nos.Contains(school))
{
school_nos.Add(school);
}
}
else
{
if (school_nos.Contains(school))
{
school_nos.Remove(school);
}
}
Session["Schools"] = school_nos;
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
它正在按預期工作到這裏。 對於下一次重新加載,我試圖用相同的數據填充下拉列表,但使用會話值顯示之前選擇的學校使用會話值,因爲我將在其他許多頁面上需要此信息。
$(document).ready(function() {
$.getJSON("/Setup/Student/GetSchool/",
function (data) {
var myData = [];
$.each(data, function (index, item) {
if (item.Selected == true) {
myData.push(item.Value);
}
});
//alert(myData);
$('#MultiSelect').selectpicker('val', myData);
});
});
和控制器;
public JsonResult GetSchool()
{
IEnumerable<SelectListItem> ListSchools = db.scasy_school
.OrderBy(a => a.name)
.Select(a => new SelectListItem { Value = a.id.ToString(), Text = a.name});
ArrayList school_nos = Session["Schools"] as ArrayList;
List<SelectListItem> ListSchoolsUpdated = new List<SelectListItem>();
foreach (var item in ListSchools)
{
SelectListItem selListItem;
if (school_nos.Contains(item.Value.ToString()))
{
selListItem = new SelectListItem() { Value = item.Value.ToString(), Text = item.Text, Selected = true };
}
else
{
selListItem = new SelectListItem() { Value = item.Value.ToString(), Text = item.Text, Selected = false };
}
ListSchoolsUpdated.Add(selListItem);
}
return Json(ListSchoolsUpdated, JsonRequestBehavior.AllowGet);
}
代碼拋出錯誤,但我不能有顯示所選項目的下拉列表。
感謝您的意見,DropDownList的是在_Layout.cshtml。 – Meliksah