我有一个名为 HtmlBlock 的模型,它有一个枚举和一个具有该枚举类型的属性。
namespace MyDandyWebsite.Models
{
public enum HtmlBlockType
{
Full_Width,
OneThird_TwoThirds,
TwoThirds_OneThird,
OneThird_OneThird_OneThird,
OneHalf_OneHalf,
OneQuarter_ThreeQuarter,
ThreeQuarter_OneQuarter,
OneQuarter_OneHalf_OneQuarter,
OneQuarter_OneQuarter_OneQuarter_OneQuarter
}
public class HtmlBlock
{
...
[Required]
public HtmlBlockType BlockType { get; set; }
...
[NotMapped]
public List<SelectListItem> DropDownItems { get; set; }
...
//Initialze class
public HtmlBlock()
{
DropDownItems = new List<SelectListItem>();
DropDownItems.Add((new SelectListItem { Text = "Full-Width", Value = "0" }));
... add the rest of the enums that are too long and wrap badly
}
}
@Html.DropDownListFor(
model => model.BlockType,
new SelectList(Model.DropDownItems,
"Value", "Text", Model.BlockType)
)
选定的块类型已正确保存到数据库中,并且除了在上面的下拉列表中(显示枚举列表中的第一项)之外的所有位置都被正确使用和列出。如果我将 HtmlBlock.BlockType 类的数据类型更改为 int,则下拉列表会正确显示,但每个简单的 displayfor 都会显示一个 int 而不是说“TwoThirds_OneThird”,这就是我想要的。
我在 google 中看到了很多解决方法,我想问是否有人知道如何使现有代码在 DropdownFor 中显示保存的值。根据我所阅读的内容,它应该可以工作。