25 December 2010 Html, MVC2 CI Team

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
            return TimeZoneInfo
                .Select(t => new SelectListItem
                    Text = t.DisplayName, Value = t.Id


public class HomeController : Controller
    public ActionResult Index()
        return View(new SettingsViewModel());

    public ActionResult Index(SettingsViewModel model)
        return View(model);

Noting special, isn't it?

The View:

<% using (Html.BeginForm()) { %>
    <%= Html.DropDownListFor(
        x => x.TimeZone,
        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.




[Download Democode]