您好,登錄后才能下訂單哦!
本篇內容主要講解“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。