【发布时间】:2020-08-27 23:39:29
【问题描述】:
我有一个如下所示的枚举:
BoT_DropdownValues.cs:
public class BoT_DropdownValues
{
public enum BlockSizes
{
[Display(Name = "12 Months")]
M12,
[Display(Name = "24 Months")]
M24,
[Display(Name = "36 Months")]
M36,
[Display(Name = "48 Months")]
M48,
[Display(Name = "60 Months")]
M60
}
我想从“选择”元素中选择一项:
CreateBoT.cshtml:
<div class="form-group" id="Q3_div">
@Html.DropDownListFor(m =>
m.BoT_Answers.Q3,
new SelectList(Enum.GetValues(typeof(BoT_DropdownValues.BlockSizes))),
"Select One",
new { @class = "custom-select", @id = "BoT_Answers_Q3" })
...
问题:
此语法在下拉列表中为我提供了“M12”、“M24”、“M36”、...。我会LIKE 向用户显示 [Display()] 名称:“12 个月”、“24 个月”等。
问:我可以使用 @Html.DropDownListFor() 的语法来实现此目的吗?
更新
我发现的大多数答案都涉及编写静态扩展类和许多额外的工作。我仍在寻找“更好的答案”,但现在这似乎给了我想要的一切:
@Html.DropDownListFor(m =>
m.BoT_Answers.Q3,
new List<SelectListItem>
{
new SelectListItem {Text="Select One", Value="", Selected=true },
new SelectListItem {Text="12 Months", Value="12" },
new SelectListItem {Text="24 Months", Value="24" },
new SelectListItem {Text="36 Months", Value="36" },
new SelectListItem {Text="48 Months", Value="48" },
new SelectListItem {Text="60 Months", Value="60" }
},
new { @class = "custom-select", @id = "BoT_Answers_Q3" })
问:谁能想到这种方法的任何缺点?
【问题讨论】:
-
看看
Html.GetEnumSelectList,也许this question会有所帮助
标签: c# asp.net-core razor