2010-03-23 38 views
7

Tôi đang cố sử dụng Html.DropDownListFor <> HtmlHelper và đang gặp một chút rắc rối khi gắn bài đăng. HTML hiển thị đúng nhưng tôi không bao giờ nhận được giá trị "đã chọn" khi gửi.MVC2 Binding không hoạt động trên 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 
         }); 
     } 
    } 

Tôi đã thử một vài điều khác nhau và chắc chắn tôi đang làm một cái gì đó ngu ngốc ... nó chỉ là không chắc chắn những gì :)

Trả lời

12

Dưới đây là một ví dụ tôi đã viết cho bạn minh họa sử dụng các phương pháp helper DropDownListFor:

mẫu:

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

Bộ điều khiển:

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

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

Xem:

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

Điều đó đã làm các trick. Tôi đã làm gì sai? – devlife

+0

Khi bạn chỉ hiển thị một phần mã của mình, tôi không thể nói điều gì sai với nó. –

+0

Tôi thấy những gì tôi đã làm sai. Thay vì làm DropDownListFor (x => x.TimeZone) tôi đã làm nó cho x.TimeZones. Cảm ơn sự giúp đỡ của Darin. – devlife

Các vấn đề liên quan