asp.net-mvc – MVC2 Binding不适用于Html.DropDownListFor <>

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – MVC2 Binding不适用于Html.DropDownListFor <>前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用 Html.DropDownListFor<> HtmlHelper和我在帖子上绑定有点麻烦. HTML呈现正确但我在提交时从未获得“选定”值.
  1. <%= Html.DropDownListFor( m => m.TimeZones,Model.TimeZones,new { @class = "SecureDropDown",name = "SelectedTimeZone" } ) %>
  1. [Bind(Exclude = "TimeZones")]
  2. public class Settingsviewmodel : ProfileBaseModel
  3. {
  4. public IEnumerable TimeZones { get; set; }
  5. public string TimeZone { get; set; }
  6.  
  7. public Settingsviewmodel()
  8. {
  9. TimeZones = GetTimeZones();
  10. TimeZone = string.Empty;
  11. }
  12.  
  13. private static IEnumerable GetTimeZones()
  14. {
  15. var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
  16. return timeZones.Select(t => new SelectListItem
  17. {
  18. Text = t.DisplayName,Value = t.Id
  19. } );
  20. }
  21. }

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

解决方法

这是我为您编写的一个示例,用于说明DropDownListFor帮助方法用法

模型:

  1. public class Settingsviewmodel
  2. {
  3. public string TimeZone { get; set; }
  4.  
  5. public IEnumerable<SelectListItem> TimeZones
  6. {
  7. get
  8. {
  9. return TimeZoneInfo
  10. .GetSystemTimeZones()
  11. .Select(t => new SelectListItem
  12. {
  13. Text = t.DisplayName,Value = t.Id
  14. });
  15. }
  16. }
  17. }

控制器:

  1. public class HomeController : Controller
  2. {
  3. public ActionResult Index()
  4. {
  5. return View(new Settingsviewmodel());
  6. }
  7.  
  8. [HttpPost]
  9. public ActionResult Index(Settingsviewmodel model)
  10. {
  11. return View(model);
  12. }
  13. }

视图:

  1. <% using (Html.BeginForm()) { %>
  2. <%= Html.DropDownListFor(
  3. x => x.TimeZone,new { @class = "SecureDropDown" }
  4. ) %>
  5. <input type="submit" value="Select timezone" />
  6. <% } %>
  7.  
  8. <div><%= Html.Encode(Model.TimeZone) %></div>

猜你在找的asp.Net相关文章