0
我有一個名爲HtmlBlock的模型,它有一個枚舉和一個具有該枚舉類型的屬性。如何在DropDownListFor中顯示保存的枚舉值
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)
)
所選blocktype被正確保存到數據庫中,並得到正確使用和每列,其中除了在上述下拉列表中,其中顯示在枚舉列表中的第一項。 如果我將類HtmlBlock.BlockType的數據類型更改爲int,那麼下拉列表將正確顯示,但每個簡單的displayfor然後顯示一個int,而不是說,「TwoThirds_OneThird」這就是我想要的。
我在谷歌中看到很多解決方法,我詢問是否有人知道如何使現有代碼顯示DropdownFor中保存的值。根據我所讀到的,它應該工作。