ASP.NET MVC Dropdownlist

 本文介绍如何在网页里显示DropDownList。

Step 1: 在Control里面添加方法 

        public ActionResult ShowDropDownList()
        {
            return View();
        }

Step 2: 在View部分添加一下代码

@Html.DropDownList("Department", new List<SelectListItem> 
{ 
    new SelectListItem {Text = "IT", Value = "1", Selected = true},
    new SelectListItem {Text = "HR", Value = "2"},
    new SelectListItem {Text = "Payroll", Value = "3"},
}, "Select Department")

 

上面部分是通过“手动”的形式添加dropdownlist的选项,如果想通过数据库读取内容,则首先添加Context, 然后通过Context获取数据表的内容。

public ActionResult ShowDropDownList()
        {
            SampleDataContext db = new SampleDataContext();
            ViewBag.Departments = new SelectList(db.Departments, "DepartmentID", "Name");
            return View();
        }
@Html.DropDownList("Departments", "Select Department")

保存在ViewBag.Departments里的数据自动显示在DropdownList里。

 

如果想让某一个项在加载的时候显示出来,可以把

ViewBag.Departments = new SelectList(db.Departments, "DepartmentID", "Name");

改成:

ViewBag.Departments = new SelectList(db.Departments, "DepartmentID", "Name", “1”);

这里“1”指的是显示项的ID。

 

但是这种方式还是比较“笨”,我们可以在表中设置一个属性叫做isSelected (如表中所示),通过每个选项的值来决定哪一个项被选定。

public ActionResult ShowDropDownList()
{
    SampleDataContext db = new SampleDataContext();
    List<SelectListItem> selectListItems = new List<SelectListItem>();
    foreach (var department in db.Departments)
    {
        SelectListItem selectListItem = new SelectListItem
        {
            Text = department.Name,
            Value = department.DepartmentID.ToString(),
            Selected = department.IsSelected.HasValue? department.IsSelected.Value : false
        };
        selectListItems.Add(selectListItem);
    }
    ViewBag.Departments = selectListItems;
    return View();
}

View端保持不变。

 

posted @ 2015-01-31 05:29  北叶青藤  阅读(219)  评论(0编辑  收藏  举报