将所有数据加载到DropDownList

时间:2017-01-20 07:54:24

标签: c# html asp.net-mvc asp.net-mvc-3

我在下面的代码工作正常。

示例输出

  

计算机系

     

技术部门

     

产品部门

我的部门是Product Department。我是登录system / project的人。可以先在DropDownList中加载我的部门吗?我在第一次加载时的意思是在加载下拉列表时我的部门被设置为第一个。

控制器

ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentDesc", null).OrderBy(m => m.Text);

HTML

@Html.DropDownList("DepartmentId ", ViewData["DepartmentId "] as SelectList, "", new { @style = "width:130px;" })

2 个答案:

答案 0 :(得分:0)

如果在新的SelectList中设置null,请设置所选的选项。

ViewBag.DepartmentId = new SelectList(db.Departments.OrderBy(m => m.Text), "DepartmentId", "DepartmentDesc", selectedDepartmentId);

答案 1 :(得分:0)

试试这段代码: -

ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentDesc",SelectedDepartmentId).OrderBy(m => m.Text);

并且

@Html.DropDownList("DepartmentId ", ViewData["DepartmentId "] as SelectList, "My Department", new { @style = "width:130px;" })