7

I'm trying to use the Html.DropDownListFor<> HtmlHelper and am having a little trouble binding on post. The HTML renders 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 :)

1 Answer 1

12

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>
2
  • As you've shown only a part of your code I cannot say what's wrong with it. Mar 23, 2010 at 13:45
  • I see what I did wrong. Rather than do the DropDownListFor(x => x.TimeZone) I did it for x.TimeZones. Thanks for the help Darin.
    – devlife
    Mar 24, 2010 at 0:08

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.