Populating a dropdown from ViewData
You can use the DropDownList html helper:
@Html.DropDownList("SelectedEmployee",
new SelectList((IEnumerable) ViewData["tempEmpList"]), "Id", "Name")
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")
The name of the dropdown ("SelectedEmployee"
) will be used when you post back your data to the server.
Set up your ViewData
in the normal way, assigning a Key name that maps to a property in your model that will be bound on Post
...
ViewData["ModelPropertyName"] = new SelectList(...)
Then in your view simply add a Html.DropDownList
...
@Html.DropDownList("ModelPropertyName")