我正在尝试使用 Html.DropDownListFor<> HtmlHelper 并且在绑定(bind)帖子时遇到了一些麻烦。 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
} );
}
}
我尝试了一些不同的事情,并且确信我在做一些愚蠢的事情......只是不确定它是什么:)
最佳答案
这是我为您编写的示例,说明了 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
});
}
}
}
Controller :
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>
关于asp.net-mvc - MVC2 绑定(bind)不适用于 Html.DropDownListFor<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2497417/