有没有办法使用DataAnnotations告诉Razor呈现DropDownList并填充特定实体中特定字段的选项?
具体来说,我在我的视图中捕获“Calendar Year”属性,并希望它是DropDownList。我现在这样做是通过ViewBag将年份传递到我的视图中,然后调用“DropDownListFor”。我希望有一种方法可以在我的ViewModel中定义它,它们只需调用“EditorFor”。
谢谢!
答案 0 :(得分:1)
我找不到使用DataAnnotation的方法,但是您不需要使用ViewBag,您可以传入值,如下所示:
@Html.ListBoxFor(m => m.SelectedFoos, Model.AllFoos.Select(f => new SelectListItem { Text = f.Name, Value = f.ID }))
(注意:这使用ListBox,taken from an answer here,但DropDownList应该类似。)