2010-03-23 27 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