asp.net-mvc - MVC2 绑定(bind)不适用于 Html.DropDownListFor<>

标签 asp.net-mvc viewmodel

我正在尝试使用 Html.DropDownListFor<> HtmlHelper 并且在绑定(bind)帖子时遇到了一些麻烦。 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 
                        } );
        }
    }

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

最佳答案

这是我为您编写的示例,说明了 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 
                });
        }
    }
}

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

关于asp.net-mvc - MVC2 绑定(bind)不适用于 Html.DropDownListFor<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2497417/

相关文章:

asp.net-mvc - MVC3 验证 - 需要组中的一个

data-binding - MVVM 在 ViewModel 构建期间或之后加载数据?

c# - 谁在 ASP MVC 5 中填充 ViewModel

javascript - 在本地存储中设置/获取 View 模型(如果存在) - knockout - javascript

c# - View 模型应该如何与存储库通信?

c# - .NET Core 托管服务和单例服务的区别

asp.net-mvc - PerRequestLifetimeManager 和 Task.Factory.StartNew - 使用 Unity 进行依赖注入(inject)

asp.net-mvc - Action()和RenderAction()之间的区别?

asp.net-mvc - 在 ASP.NET MVC 中返回 FileResult 的错误消息/页面

asp.net-mvc-3 - 为什么有两个类, View 模型和域模型?