最新下载
热门教程
- 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());}}}
相关文章
- 幻想生活i前期快速解锁职业指南 07-04
- 污痕圣杯阿瓦隆的陨落强力召唤物推荐 07-04
- 燕云十六声生财之道万事知窦万金位置一览 07-04
- BLCoin(BLB币)的交易量 07-04
- XRP价格动态:加密货币老手将2美元买入XRP比作50美元购入比特币——XRP能否复制BTC的崛起之路? 07-04
- 云顶之弈摇摆灵动阵容搭配推荐 07-04