asp.net-mvc 从 ViewData 填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12090937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populating a dropdown from ViewData
提问by JustAnotherDeveloper
I have viewdata in my controller which is populated by a list:
我的控制器中有视图数据,它由一个列表填充:
List<employee> tempEmpList = new List<employee>();
tempEmpList = context.employees.ToList();
ViewData["tempEmpList"] = tempEmpList;
and I am passing this into my view, the question is, how do I place the content of the viewdata list into a dropdown list?
我将它传递到我的视图中,问题是,如何将 viewdata 列表的内容放入下拉列表中?
The display data will be .namefrom the list item.
显示数据将.name来自列表项。
I know I could do a foreachon the Viewdata and create a select list, but this seems a bit long winded
我知道我可以foreach在 Viewdata 上做一个并创建一个选择列表,但这似乎有点冗长
回答by nemesv
You can use the DropDownListhtml helper:
您可以使用DropDownListhtml 助手:
@Html.DropDownList("SelectedEmployee",
new SelectList((IEnumerable) ViewData["tempEmpList"]), "Id", "Name")
In the SelectListconstructor, you can specify which properties of the Employeeclass should be used as both the text and the value within the dropdown (e.g. "Id", "Name")
在SelectList构造函数中,您可以指定Employee类的哪些属性应用作下拉列表中的文本和值(例如“Id”、“Name”)
The name of the dropdown ("SelectedEmployee") will be used when you post back your data to the server.
"SelectedEmployee"当您将数据回发到服务器时,将使用下拉列表 ( )的名称。
回答by JDandChips
Set up your ViewDatain the normal way, assigning a Key name that maps to a property in your model that will be bound on Post...
ViewData以正常方式设置您的,分配一个映射到您的模型中的属性的键名称,该属性将绑定到Post...
ViewData["ModelPropertyName"] = new SelectList(...)
Then in your view simply add a Html.DropDownList...
然后在您的视图中只需添加一个Html.DropDownList...
@Html.DropDownList("ModelPropertyName")
回答by Sapnandu
Please try with that. I have tried with MVC5
请尝试一下。我已经尝试过 MVC5
@Html.DropDownList("SelectedEmployee", new SelectList((System.Collections.IEnumerable) ViewData["tempEmpList"],"id","Name"))
@Html.DropDownList("SelectedEmployee", new SelectList((System.Collections.IEnumerable) ViewData["tempEmpList"],"id","Name"))

