ASP.NET MVC實(shí)現(xiàn)下拉框多選
我們知道,在ASP.NET MVC中實(shí)現(xiàn)多選Select的話,使用Html.ListBoxFor或Html.ListBox方法就可以。在實(shí)際應(yīng)用中,到底該如何設(shè)計(jì)View Model, 控制器如何接收多選Select的選中項(xiàng)呢?
實(shí)現(xiàn)效果如下:
初始狀態(tài)某些選項(xiàng)被選中。
當(dāng)按著ctrl鍵,進(jìn)行重新選擇多項(xiàng),點(diǎn)擊"提交"按鈕,把選中項(xiàng)的id拼接。
對(duì)于Select中的項(xiàng),包含顯示值,Value值,以及是否選中,抽象成如下的類。
public class City {public int Id { get; set; }public string Name { get; set; }public bool IsSelected { get; set; } }
對(duì)于整個(gè)多選Select來(lái)說(shuō),在ASP.NET MVC中,所有的選項(xiàng)被看作SelectListItem類型,選中的項(xiàng)是一個(gè)string類型的集合。于是多選Select的View Model設(shè)計(jì)為:
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 = "濟(jì)南", 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中,是一個(gè)CityVm的強(qiáng)類型視圖,對(duì)于選中的項(xiàng)會(huì)以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中,再把從視圖傳遞過(guò)來(lái)的IEnumerable<string>拼接并呈現(xiàn)。
public class HomeController : Controller {......[HttpPost]public ActionResult GetCities(IEnumerable<string> selectedCities){ if (selectedCities == null) {return Content("沒(méi)有選中任何選項(xiàng)"); } else {StringBuilder sb = new StringBuilder();sb.Append("選中項(xiàng)的Id是:" + string.Join(",", selectedCities));return Content(sb.ToString()); }} }
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章:
1. ASP.NET MVC實(shí)現(xiàn)區(qū)域或城市選擇2. 使用EF Code First搭建簡(jiǎn)易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫(kù)遷移3. ASP.NET MVC使用Quartz.NET執(zhí)行定時(shí)任務(wù)4. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條5. ASP.Net MVC利用NPOI導(dǎo)入導(dǎo)出Excel的示例代碼6. ASP.NET MVC實(shí)現(xiàn)樹形導(dǎo)航菜單7. ASP.NET MVC使用Log4Net記錄異常日志并跳轉(zhuǎn)到靜態(tài)頁(yè)8. ASP.NET MVC增加一條記錄同時(shí)添加N條集合屬性所對(duì)應(yīng)的個(gè)體9. ASP.NET MVC實(shí)現(xiàn)城市或車型三級(jí)聯(lián)動(dòng)10. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車
