我有一个名为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)
)
所选的blocktype被正确保存到数据库中,并且在上面的下拉列表中除了显示枚举列表中的第一个项目之外的每个地方都被正确使用和列出。 如果我将类HtmlBlock.BlockType的数据类型更改为int,则下拉列表会正确显示,但每个简单的显示然后显示一个int,而不是说,&#34; TwoThirds_OneThird&#34;这就是我想要的。
我在google中看到了很多变通方法,我问是否有人知道如何让现有代码在DropdownFor中显示保存的值。根据我所读到的,它应该有用。
答案 0 :(得分:0)
http://www.asp.net/mvc/overview/releases/mvc51-release-notes
安装MVC 5.1并使用@ Html.EnumDropDownListFor