Asp.net MVC5中Html.DropDownList的使用

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   os   io   使用   strong   

一.靜態下拉式清單項的綁定

在下拉式清單中綁定靜態項,我們可以通過 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 中的表單中更改下拉式清單項AutoPostBack,我們可以在 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

Asp.net MVC5中Html.DropDownList的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.