在視圖的Model<Vo>里面我們需要使用IEnumerable來將別的列表的數(shù)據(jù)全部的轉(zhuǎn)化為下拉列表。下面是關(guān)于在項目中實際的寫法。
一:實現(xiàn)下拉屬性列表的寫法
通過使用SelectListItem來自動填充到DropDownList中,形成下拉框。
我們想要在前臺頁面將數(shù)據(jù)變?yōu)橄吕鸵玫紻ropDownList這個特性標(biāo)簽來實現(xiàn),但是使用的前提是要在Action里面進行設(shè)置,對Value和Text進行賦值。
下面是屬性的寫法,是IEnumerable<>接口類型
public class CreatCustomerView { public CreatCustomerView() { this.Schools = new List<SelectListItem>(); } /// <summary> /// 外鍵 /// </summary> [Display(Name = "學(xué)校"), Required(ErrorMessage = "不能選擇為空")] public Guid SchoolId { get; set; } /// <summary> /// 學(xué)校的導(dǎo)航屬性 /// </summary> public IEnumerable<SelectListItem> Schools { get; set; } /// <summary> /// OpenId:跟微信綁定的唯一表示,從微信處獲取 /// </summary> public string OpenId { get; set; } }
寫成這樣就是想將其Schools放在一個集合里面,而且在上面初始化的時候?qū)懗闪薙electListItem。
SelectListItem代表System.Web.Mvc的實例的選擇項。SelectList類。這里將在Action里面進行相關(guān)的設(shè)置。
IEnumerable<T>接口類型:這個是實現(xiàn)Foreach遍歷所必須的,因為所有的集合和數(shù)據(jù)都繼承自這個接口,并且支持非泛型方法的簡單迭代,是集合訪問器。定義一種擴展方法,用來對數(shù)據(jù)集合中元素進行遍歷,過濾,排序,搜索等操作。
二:在Action里面的寫法
這里就是為其Value和Text進行賦值。
public ActionResult ChooseSchool() { var entity = new CreatCustomerView(); entity.Schools = _schoolService.GetAll() .Where(x => x.Id != Guid.Empty) .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList(); return View(entity); }
首先通過GetALL方法來取出數(shù)據(jù)庫表中的數(shù)據(jù),通過Select對其進行賦值,轉(zhuǎn)換為ToList()的形式,在將其傳到視圖。這里就是為其里面賦值,為將來在前臺頁面進行Foreach做準(zhǔn)備。
三:View視圖里面的寫法
在視圖里面是通過HtmlHelper中的DropDownList來實現(xiàn)的,但是DropDownList的現(xiàn)實要通過下面的三個步奏來實現(xiàn)。
其實就是前面兩個步奏中的內(nèi)容,下面是View中的代碼。
@{ ViewBag.Title = "選擇學(xué)校"; Layout = "~/Views/Shared/_LayoutNew.cshtml";}@using System.Runtime.InteropServices@model ExPRess.Weixin.Web.Models.CreatCustomerView<div class="header"><a href="@Url.Action("Index","Member")" class="btn btn-link btn-xs pull-left">返回</a>選擇學(xué)校</div>@using (Html.BeginForm(null, null, FormMethod.Post)){ <input type="hidden" value="@ViewBag.OpenId" name="OpenId" /> <div class="col-sm-5 center" style="margin: auto;position: absolute; top: 0; left: 0; bottom: 0; right: 0; "> <br/><br/><br /> @Html.LabelFor(x => x.SchoolId) @Html.DropDownListFor(x => x.SchoolId, Model.Schools, new { @class = "form-control" }) @Html.ValidationMessageFor(x => x.SchoolId) <br/> <input type="submit" class="btn btn-success btn-sm btn-block" value="選擇學(xué)校"/> </div>}
通過里面的@Html.DropDownListFor(x => x.SchoolId, Model.Schools, new { @class = "form-control" }) 來實現(xiàn)下拉的結(jié)果。
四:顯示結(jié)果
附件:DropDownList知識參考資料 http://www.survivalescaperooms.com/kirinboy/archive/2009/10/28/use-dropdownlist-in-asp.net-mvc.html
新聞熱點
疑難解答