Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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 :)

like image 400
devlife Avatar asked Mar 23 '10 03:03

devlife


1 Answers

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>
like image 181
Darin Dimitrov Avatar answered Oct 03 '22 08:10

Darin Dimitrov