2010-03-23 56 views
7

我想要使用Html.DropDownListFor <> HtmlHelper,并有一些麻烦绑定后。 HTML呈现正常,但在提交时从未获得“选定”值。MVC2绑定不工作Html.DropDownListFor <>

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

我已经尝试了一些不同的事情,我相信我在做一些愚蠢的事......它只是不知道什么:)

回答

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> 
+0

该诀窍。我做错了什么? – devlife 2010-03-23 13:41:17

+0

正如你只显示了你的代码的一部分,我不能说它有什么问题。 – 2010-03-23 13:45:02

+0

我明白我做错了什么。而不是做DropDownListFor(x => x.TimeZone)我做了x.TimeZones。感谢Darin的帮助。 – devlife 2010-03-24 00:08:42

相关问题