最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
ASP.NET M5C实现下拉框多选
时间:2023-09-04 09:04:42 编辑:袖梨 来源:一聚教程网
我们知道,在ASP.NET MVC中实现多选Select的话,使用Html.ListBoxFor或Html.ListBox方法就可以。在实际应用中,到底该如何设计View Model, 控制器如何接收多选Select的选中项呢?
实现效果如下:
初始状态某些选项被选中。
当按着ctrl键,进行重新选择多项,点击"提交"按钮,把选中项的id拼接。
对于Select中的项,包含显示值,Value值,以及是否选中,抽象成如下的类。
public class City{public int Id { get; set; }public string Name { get; set; }public bool IsSelected { get; set; }}
对于整个多选Select来说,在ASP.NET MVC中,所有的选项被看作SelectListItem类型,选中的项是一个string类型的集合。于是多选Select的View Model设计为:
public class CityVm{public IEnumerable<SelectListItem>Cities { get; set; }public IEnumerable<string> SelectedCities { get; set; }}
在HomeController中,把SelectListItem的集合赋值给CityVm的Cities属性。
public class HomeController : Controller{public ActionResult Index(){var cities = new List<City>{new City(){Id = 1, Name = "青岛", IsSelected = true},new City(){Id = 2, Name = "胶南", IsSelected = false},new City(){Id = 3, Name = "即墨", IsSelected = true},new City(){Id = 4, Name = "黄岛", IsSelected = false},new City(){Id = 5, Name = "济南", IsSelected = false}};var citiesToPass = from c in citiesselect 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);}......}
在Home/Index.cshtml中,是一个CityVm的强类型视图,对于选中的项会以IEnumerable<string>集合传递给控制器。
@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="提交"/>}
在HomeController中,再把从视图传递过来的IEnumerable<string>拼接并呈现。
public class HomeController : Controller{......[HttpPost]public ActionResult GetCities(IEnumerable<string> selectedCities){if (selectedCities == null){return Content("没有选中任何选项");}else{StringBuilder sb = new StringBuilder();sb.Append("选中项的Id是:" + string.Join(",", selectedCities));return Content(sb.ToString());}}}
相关文章
- 人们熟悉的寄居蟹属于以下哪种分类 神奇海洋11月21日答案 11-21
- 第五人格11.22共研服有什么更新 11月22日共研服更新内容介绍 11-21
- 原神恰斯卡怎么培养 11-21
- 无期迷途四星装束是谁 11-21
- 王者荣耀帝丹高中校服怎么获得 11-21
- 光遇姆明季后续版本怎么玩 11-21