MVC2 Binding不适用于Html.DropDownListFor<>

时间:2010-03-23 03:33:33

标签: asp.net-mvc viewmodel

我正在尝试使用Html.DropDownListFor<> HtmlHelper和我在帖子上绑定有点麻烦。 HTML呈现正确但我在提交时从未获得“选定”值。

<%= 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 
                        } );
        }
    }

我尝试了一些不同的事情,并确信我做的事情很愚蠢...只是不确定它是什么:)

1 个答案:

答案 0 :(得分:12)

这是我为您编写的一个示例,用于说明DropDownListFor帮助方法的用法:

型号:

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 
                });
        }
    }
}

控制器:

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

    [HttpPost]
    public ActionResult Index(SettingsViewModel model)
    {
        return View(model);
    }
}

查看:

<% 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>