HowTo: apply MVC2 & Html.DropDownListFor
First of all: Merry Christmas to all of you out there and to your family ![]()
In an ASP.NET MVC framework you will find a lot of nice HTML Helper. Even one which will help you building a simple HTML <select>. But how does the DropDownListFor helper work?
Mhh.. WTF?
To say the true: It takes a while to understand this intellisense for me as well. Maybe it’s because Im not such a smart-ace ![]()
![]()
After spending some time on google queries I found this solution on Stackoverflow.
The Model:
public class SettingsViewModel
{
public string TimeZone { get; set; }
public IEnumerable<SelectListItem> TimeZones
{
get
{
return TimeZoneInfo
.GetSystemTimeZones()
.Select(t => new SelectListItem
{
Text = t.DisplayName, Value = t.Id
});
}
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new SettingsViewModel());
}
[HttpPost]
public ActionResult Index(SettingsViewModel model)
{
return View(model);
}
}
Noting special, isn’t it?
The View:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(
x => x.TimeZone,
Model.TimeZones,
new { @class = "SecureDropDown" }
) %>
<input type="submit" value="Select timezone" />
<% } %>
<div><%= Html.Encode(Model.TimeZone) %></div>
First we need to declare where the “selected” element should be mapped → on TimeZone. Second we have the list with the probably results. In the last step you are able to pass some Html attributes.
Result:
Fascinating!



satish
January 7, 2011
Hi
the article is good and helped me a lot, however in the place of controller code you have copied the view code. check this.
Code Inside Team
January 10, 2011
@satish: thanks a lot for your help. I fixed it now. Greetings Antje
Christof
January 10, 2011
Hi,
could you prepare such an example with a SELECTED value in in the drop-down ? I have such a case in which i want to have one value selected but i don´t get it working
Thanks
pat
June 1, 2011
Selected Item
list.Add(new SelectListItem { Selected = (selected ==sLine), Text = sLine, Value = sLine});