【问题标题】:MVC2 Binding isn't working for Html.DropDownListFor<>MVC2 绑定不适用于 Html.DropDownListFor<>
【发布时间】:2010-03-23 03:33:33
【问题描述】:

我正在尝试使用 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 
                        } );
        }
    }

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

【问题讨论】:

    标签: asp.net-mvc viewmodel


    【解决方案1】:

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

    【讨论】:

    • 因为你只展示了你的代码的一部分,我不能说它有什么问题。
    • 我明白我做错了什么。我没有为 x.TimeZones 做 DropDownListFor(x => x.TimeZone)。感谢达林的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2017-06-19
    • 2016-02-24
    • 2015-01-06
    相关资源
    最近更新 更多