Im ASP.NET MVC Framework verbergen sich allerhand netter Html Helper. Darunter auch eins um eine simples HTML <select> zu basteln. Doch wie setz ich nun den DropDownListFor Helper ein?
Mhh... WTF?
Also so richtig "klar” war mir die Intellisense hier nicht - wahrscheinlich bin ich nicht so ein Smart-Ass ;)
Nach ein paar Google Queries hatte ich dann die Lösung auf Stackoverflow gefunden. Ich blogg die mal hier, damit ich es nicht vergesse.
Das 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
});
}
}
}Im "TimeZone” Property wird das eigentliche Ergebnis gespeichert. Die TimeZones Liste ist nur für das DropDown gedacht.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new SettingsViewModel());
}
[HttpPost]
public ActionResult Index(SettingsViewModel model)
{
return View(model);
}
}Nix besonders, oder?
Der 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>Als erstes wird festgelegt, wohin das "selected” Element gemappt wird -> auf TimeZone. Als zweites kommt die Liste an möglichen Werten. Als letztes können noch HtmlAttribute mitgegeben werden.
Ergebnis:
Fetzt, oder?