MVC2 Binding isn't working for Html.DropDownListFor<>
I'm trying to use the Html.DropDownListFor<> HtmlHelper and am having a little trouble binding on post. The HTML render开发者_运维技巧s properly but I never get a "selected" value when submitting.
<%= Html.DropDownListFor( m => m.TimeZones,
Model.TimeZones,
new { @class = "SecureDropDown",
name = "SelectedTimeZone" } ) %>
[Bind(Exclude = "TimeZones")]
public class SettingsViewModel : ProfileBaseModel
{
public IEnumerable TimeZones { get; set; }
public string TimeZone { get; set; }
public SettingsViewModel()
{
TimeZones = GetTimeZones();
TimeZone = string.Empty;
}
private static IEnumerable GetTimeZones()
{
var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
return timeZones.Select(t => new SelectListItem
{
Text = t.DisplayName,
Value = t.Id
} );
}
}
I've tried a few different things and am sure I am doing something stupid... just not sure what it is :)
Here's an example I wrote for you illustrating the usage of DropDownListFor helper method:
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);
}
}
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>
精彩评论