最近需要用到多選框,Asp.Net MVC自帶的@Html.ListBox或@Html.ListBoxFor的顯示效果太差,於是找到了Select2進行優化,並正式了解了多選框的操作方法。
首先介紹多選框的操作方法;
一、定義一個MultipleSelectModel
public class MultipleSelectModel { public int[] MultipleItem { get; set; } }
二、在Controller中實例化MultiSelectList
public ActionResult MultipleSelectView() { //實際可從數據庫取數填充 List<SelectListItem> listBox = new List<SelectListItem>(); for (int i = 0; i < 4; i++) { var temp = new SelectListItem { Value = i.ToString(), Text = "第" + i.ToString() }; listBox.Add(temp); } //定義已選數據 var viewModel = new MultipleSelectModel(); viewModel.MultipleItem = new int[] { 0, 1 }; ViewBag.MultiSelecteTest = new MultiSelectList(listBox, "Value", "Text"); return View(viewModel); }
三、View中利用@Html.ListBoxFor()可初始化已選項
@model Models.ViewModel.MultipleSelectModel @{ ViewBag.Title = "MultipleSelectView"; Layout = "~/Views/Shared/_Layout.cshtml"; }<h2>MultipleSelectView</h2> @Html.ListBoxFor(model => model.MultipleItem, ViewBag.MultiSelecteTest as MultiSelectList, new { @class = "form-control multiple-select"})
四、利用Select2美化多選框
1、首先引用Select2的css文件及javascript文件,教學因素,沒有將select2放在BundleConfig中
@Styles.Render("~/Content/jqueryui") @Styles.Render("~/Content/select2") @section scripts{ <script src="~/Scripts/select2.min.js"></script> }
2、簡單使用Select2
<script type="text/javascript"> $(document).ready(function () { $('.multiple-select').select2(); }); </script>
五、效果圖
六、用Ajax刷新分頁視圖中如何使用到Select2
1、利用Ajax.BegionForm中的OnComplete,調用selectDeviceSuccess的jQuery方法
@using (Ajax.BeginForm("_PartialViewAction", "ViewTestr", new AjaxOptions() { HttpMethod = "POST", OnComplete = "selectDeviceSuccess" }, new { enctype = "multipart/form-data" }))
2、selectDeviceSuccess中再次使用Select2
function selectDeviceSuccess() { $('.multiple-select').select2({ language: 'zh-CN' }); }
七、總結
@Html.ListBoxFor封裝了初始化過程,傳到後台的數據是數組int[] MultipleItem。用$('.multiple-select').val()獲得選中值以','分隔。