本篇内容主要讲解“ASP.NET MVC如何实现多选下拉框”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“ASP.NET MVC如何实现多选下拉框”吧!
借助Chosen Plugin可以实现多选下拉框。
设置选项数量,比如设置最多允许2个选项:
考虑到多选下拉<select multiple="multiple"...></select>选中项是string数组,Model应该这样设计:
using System.Collections.Generic; using System.Web.Mvc; namespace MvcApplication1.Models { public class CarVm { public string[] SelectedCars { get; set; } public IEnumerable<SelectListItem> AllCars { get; set; } } }
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class HomeController : Controller { public ActionResult Index() { CarVm carVm = new CarVm(); carVm.SelectedCars = new string[]{"1","2"}; carVm.AllCars = GetAllCars(); return View(carVm); } [HttpPost] public ActionResult SaveCars(CarVm carVm) { if (ModelState.IsValid) { return View(carVm); } return RedirectToAction("Index", carVm); } private IEnumerable<SelectListItem> GetAllCars() { List<SelectListItem> allCars = new List<SelectListItem>(); allCars.Add(new SelectListItem() {Value = "1",Text = "奔驰"}); allCars.Add(new SelectListItem() { Value = "2", Text = "宝马" }); allCars.Add(new SelectListItem() { Value = "3", Text = "奇瑞" }); allCars.Add(new SelectListItem() { Value = "4", Text = "比亚迪" }); allCars.Add(new SelectListItem() { Value = "5", Text = "起亚" }); allCars.Add(new SelectListItem() { Value = "6", Text = "大众" }); allCars.Add(new SelectListItem() { Value = "7", Text = "斯柯达" }); allCars.Add(new SelectListItem() { Value = "8", Text = "丰田" }); allCars.Add(new SelectListItem() { Value = "9", Text = "本田" }); return allCars.AsEnumerable(); } } }
Home/Index.cshtml视图中,需要引用Chosen Plugin的css和js文件:
@model MvcApplication1.Models.CarVm @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h3>Index</h3> <link href="~/Content/chosen.css" rel="external nofollow" rel="stylesheet" /> @using (Html.BeginForm("SaveCars", "Home", FormMethod.Post)) { @Html.LabelFor(m => m.SelectedCars,"最多选择2个选项") <br/> @Html.ListBoxFor(m => m.SelectedCars, Model.AllCars, new {@class="chosen", multiple="multiple", }) <br/> <input type="submit" value="提交"/> } @section scripts { <script src="~/Scripts/chosen.jquery.min.js"></script> <script type="text/javascript"> $(function() { $('.chosen').chosen({ max_selected_options: 2 }); $(".chosen-deselect").chosen( { allow_single_deselect: true }); $(".chosen").chosen().change(); $(".chosen").trigger('liszt:updated'); }); </script> }
到此,相信大家对“ASP.NET MVC如何实现多选下拉框”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。