Implement Multi-Select and mvcselect in ASP. net mvc.
We know that, if you implement multiple Select statements in ASP. net mvc, you can use the Html. ListBoxFor or Html. ListBox methods. In practical applications, how should we design a View Model? How can the Controller receive the selected items of multiple Select statements?
The implementation result is as follows:
Some options in the initial status are selected.
Press ctrl to reselect multiple items and click Submit to splice the id of the selected item.
For items in the Select statement, including the display Value, Value, and whether to Select the items, the items are abstracted into the following classes.
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
In ASP. net mvc, all the options are considered as SelectListItem type, and the selected items are a collection of string types. Therefore, the View Model with multiple Select statements is designed as follows:
public class CityVm
{
public IEnumerable<SelectListItem> Cities { get; set; }
public IEnumerable<string> SelectedCities { get; set; }
}
In HomeController, assign the set of SelectListItem 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, it is a strong type view of CityVm. The selected items are passed to the controller using the IEnumerable <string> set.
@model MvcApplication1.Models.CityVm
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@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 = "submit"/>
}
In HomeController, The IEnumerable <string> passed from the view is 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());
}
}
}