本文介绍了从 ViewData 填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有视图数据,它由一个列表填充:

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;

并且我将其传递到我的视图中,问题是,如何将 viewdata 列表的内容放入下拉列表中?

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?

显示数据将是列表项中的 .name.

The display data will be .name from the list item.

我知道我可以在 Viewdata 上执行 foreach 并创建一个选择列表,但这似乎有点啰嗦

I know I could do a foreach on the Viewdata and create a select list, but this seems a bit long winded

推荐答案

您可以使用 DropDownList html 助手:

You can use the DropDownList html helper:

@Html.DropDownList("SelectedEmployee",
    new SelectList((IEnumerable) ViewData["tempEmpList"]), "Id", "Name")

SelectList 构造函数中,您可以指定 Employee 类的哪些属性应用作下拉列表中的文本和值(例如Id"、"姓名")

In the SelectList constructor, you can specify which properties of the Employee class should be used as both the text and the value within the dropdown (e.g. "Id", "Name")

下拉列表的名称 ("SelectedEmployee") 将在您将数据回发到服务器时使用.

The name of the dropdown ("SelectedEmployee") will be used when you post back your data to the server.

这篇关于从 ViewData 填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:02