We know that using the Html.listboxfor or Html.listbox method is possible if you are implementing multiple select selections in ASP. In the actual application, how to design the view Model, how the controller receives the selection of multiple select?
The implementation results are as follows:
Initial state some options are selected.
When you press the CTRL key to re-select multiple items, click the "Submit" button, the ID of the selected item is spliced.
For the item in select, contains the display value, value, and whether it is selected, and is abstracted into the following class.
public class city
{
public int Id {get; set;}
public string Name {get; set;}
public bool IsSelected {get; set;}
}
For the entire multi-select Select, all options are treated as selectlistitem types in ASP. NET MVC, and the selected item is a collection of string types. The view model of the multiple select Selects is designed to:
public class CITYVM
{
Public IEnumerable<SelectListItem> Cities {get; set;}
Public IEnumerable<string> selectedcities {get; set;}
}
In HomeController, the SelectListItem collection is assigned to the cities attribute of CITYVM.
public class Homecontroller:controller
{
Public ActionResult Index ()
{
var cities = new List<City>
{
New City () {Id = 1, Name = "Qingdao", IsSelected = true},
New City () {Id = 2, Name = "Jiaonan", IsSelected = false},
New City () {Id = 3, Name = "Jimo", IsSelected = true},
New City () {Id = 4, Name = "Huangdao", IsSelected = false},
New City () {Id = 5, Name = "Jinan", IsSelected = false}
};
var citiestopass = from C in cities
Select New SelectListItem () {Text = c.name, Value = c.id.tostring (), Selected = c.isselected};
CITYVM CITYVM = new CITYVM ();
Cityvm.cities = Citiestopass;
Viewdata["CC"] = Citiestopass.count ();
Return View (CITYVM);
}
......
}
In Home/index.cshtml, is a strongly-typed view of CITYVM that is passed to the controller with the Ienumerable<string> collection for the selected item.
@model MvcApplication1.Models.CityVm
@{
Viewbag.title = "Index";
Layout = "~/views/shared/_layout.cshtml";
}
< H2 > Index</h2>
@using (Html.BeginForm ("GetCities", "Home", FormMethod.Post, new {id = "myForm"}))
{
@Html. listboxfor (c = c.selectedcities, model.cities, new {size = viewdata["CC"]})
< BR />
< input type="submit"value="commit"/>
}
In HomeController, the ienumerable<string> that are passed from the view are spliced and rendered.
public class Homecontroller:controller
{
......
[HttpPost]
Public ActionResult getcities (IEnumerable<string> selectedcities)
{
if (selectedcities = = null)
{
Return Content ("No options selected");
}
Else
{
StringBuilder sb = new StringBuilder ();
Sb. Append ("The ID of the selected item is:" + string.) Join (",", selectedcities));
Return Content (sb.) ToString ());
}
}
}
Implementing select multiple selection in ASP.