ASP.NET MVC Dropdownlist

时间:2023-03-09 22:47:11
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 = "", Selected = true},
new SelectListItem {Text = "HR", Value = ""},
new SelectListItem {Text = "Payroll", Value = ""},
}, "Select Department")

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

ASP.NET MVC Dropdownlist

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”指的是显示项的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端保持不变。