利用Select2优化@Html.ListBoxFor显示,学会用MultiSelectList

2016-12-28 07:37:53来源:cnblogs.com作者:哈哈兮人点击

最近需要用到多选框,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()获得选中值以','分隔。

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台