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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。