Multi-select drop-down boxes can be implemented with chosen plugin.
Select multiple items:
Set the number of options, such as setting a maximum of 2 options:
Considering the multi-select dropdown <select multiple= "multiple" ...></select> the selected item is a string array, the model should be designed like this:
usingSystem.Collections.Generic;usingSYSTEM.WEB.MVC;namespacemvcapplication1.models{ Public classCARVM { Public string[] Selectedcars {Get;Set; } PublicIenumerable<selectlistitem> Allcars {Get;Set; } }}
In HomeController:
usingSystem.Collections.Generic;usingSystem.Linq;usingSYSTEM.WEB.MVC;usingMvcapplication1.models;namespacemvcapplication1.controllers{ Public classHomecontroller:controller { PublicActionResult Index () {CARVM CARVM=NewCARVM (); Carvm.selectedcars=New string[]{"1","2"}; Carvm.allcars=Getallcars (); returnView (CARVM); } [HttpPost] Publicactionresult savecars (CARVM carvm) {if(modelstate.isvalid) {returnView (CARVM); } returnRedirecttoaction ("Index", CARVM); } PrivateIenumerable<selectlistitem>Getallcars () {List<SelectListItem> Allcars =NewList<selectlistitem>(); Allcars.add (NewSelectListItem () {Value ="1", Text ="Mercedes"}); Allcars.add (NewSelectListItem () {Value ="2", Text ="BMW" }); Allcars.add (NewSelectListItem () {Value ="3", Text ="Chery" }); Allcars.add (NewSelectListItem () {Value ="4", Text ="BYD" }); Allcars.add (NewSelectListItem () {Value ="5", Text ="Kia" }); Allcars.add (NewSelectListItem () {Value ="6", Text ="Volkswagen" }); Allcars.add (NewSelectListItem () {Value ="7", Text ="Skoda" }); Allcars.add (NewSelectListItem () {Value ="8", Text ="Toyota" }); Allcars.add (NewSelectListItem () {Value ="9", Text ="Honda" }); returnallcars.asenumerable (); } }}
In the home/index.cshtml view, you need to refer to the CSS and JS files of chosen plugin:
@model mvcapplication1.models.carvm@{viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}"~/content/chosen.css"Rel="stylesheet"/>@using (Html.BeginForm ("Savecars","Home", FormMethod.Post)) {@Html. labelfor (M= M.selectedcars,"Select a maximum of 2 options") <br/>@Html. listboxfor (M= M.selectedcars, Model.allcars,New{@class ="Chosen", multiple="multiple", style="width:350px;"}) <br/> <input type="Submit"Value="Submit"/>} @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>}