Asp.net MVC5中Html.DropDownList的使用


一.靜態下拉列表項的綁定

在下拉列表中綁定靜態項,我們可以通過 SelectListItem 的集合作為數據源的下拉列表。
1     @Html.DropDownList("dropRoles", new List<SelectListItem>()
2     {
3         new SelectListItem() { Text= "Yes", Value = "true" },
4         new SelectListItem() { Text= "No", Value = "false", Selected = true }
5     }, "Select ..."),new { @class = "myClass", style = "width: 250px;" })

 在上面的代碼片段中,

第一個參數是下拉列表中的名稱;

第二個參數是 SelectListItem 要用作數據源的下拉列表中的集合和第三個參數是默認值,如果將選中"選擇 = true"不在任何的 SelectListItem 中指定。

第三個參數是在下拉列表中顯示的默認默認空項。

第四個參數是寫入下拉列表中的樣式/類或其他 HTML 屬性( htmlObjectAttributes)。

二、綁定多個表數據

 @Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList)

 控制器操作方法代碼

var data = from p in db.PersonalDetails
                       join f in db.Files
                       on p.AutoId equals f.PersonalDetailsId
                       select new 
                       {
                           PersonName = p.FirstName,
                           MyFileName = f.FileName
                       };

            SelectList list = new SelectList(data, "MyFileName", "PersonName");
            ViewBag.Roles = list;

 

在上面的代碼片段中,我們加入了兩個表使用 LINQ,形成具有到 PersonName 和 MyFileName 屬性的對象。轉換成通過指定dataTextFileld dataValueField 的下拉列表。
 此時集合然后被設置為 ViewBag.Roles,用作數據源的下拉列表中的視圖。
 

三、在下拉列表中綁定模型

在下拉列表中綁定一個模型屬性,使用下面的代碼片段。
public IEnumerable<SelectListItem> Categories { get; set; }
在該控制器的操作方法中設置此屬性值,
model.Categories = db.CategoryModels.Where(c => c.SectionId == sectionId &&
 c.Active == true).OrderBy(ct => ct.CategoryName).ToList().
Select(x => new SelectListItem { Value = x.CategoryId.ToString(), Text = x.CategoryName }).ToList();
在上面的代碼片段中,注意第三行的代碼中,是從列表中選擇的所有項目,創建SelectListItem 對象所指定的值為類別 id 和類別名稱作為文本。
 
當此集合有界的下拉列表中時,類別 id 作為項的值和類別名稱用作下拉列表項的文本。
四、更改下拉列表項的回發

 在 ASP.NET MVC 中的窗體中更改下拉列表項自動回發,我們可以在 htmlObjectAttributes 中這樣指定 onchange 屬性。

@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList, "Select ...", 
new { @class = "myClass", style = "width: 250px;", onchange = "this.form.submit();" })
在上面的代碼片段,onchange 屬性會迫使該窗體以提交它在服務器上,當用戶更改下拉列表中的選定內容。
 
本文參考:http://www.dotnetfunda.com/articles/show/2918/working-with-dropdownlist-in-aspnet-mvc
相關資源:http://www.cnblogs.com/kirinboy/archive/2009/10/28/use-dropdownlist-in-asp-net-mvc.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM