ASP.NET MVC实现下拉框多选
- 技术交流
- 2024-10-01 09:39:02
我们知道,在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 IEnumerableCities { get; set; } public IEnumerable SelectedCities { get; set; } }
在HomeController中,把SelectListItem的集合赋值给CityVm的Cities属性。
public class HomeController : Controller { public ActionResult Index() { var cities = new List{ 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 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); } ...... }
在Home/Index.cshtml中,是一个CityVm的强类型视图,对于选中的项会以IEnumerable
@model MvcApplication1.Models.CityVm @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; }Index
@using (Html.BeginForm("GetCities", "Home", FormMethod.Post, new {id = "myForm"})) { @Html.ListBoxFor(c => c.SelectedCities, Model.Cities, new {size = ViewData["cc"]})
}
在HomeController中,再把从视图传递过来的IEnumerable
public class HomeController : Controller { ...... [HttpPost] public ActionResult GetCities(IEnumerableselectedCities) { if (selectedCities == null) { return Content("没有选中任何选项"); } else { StringBuilder sb = new StringBuilder(); sb.Append("选中项的Id是:" + string.Join(",", selectedCities)); return Content(sb.ToString()); } } }
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对讯客的支持。如果你想了解更多相关内容请查看下面相关链接
ASP.NET MVC实现下拉框多选由讯客互联技术交流栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“ASP.NET MVC实现下拉框多选”