【问题标题】:How to display saved enum value in DropDownListFor如何在 DropDownListFor 中显示保存的枚举值
【发布时间】:2014-05-05 21:51:52
【问题描述】:

我有一个名为 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 中保存的值。根据我阅读的内容,它应该可以工作。

【问题讨论】:

    标签: enums asp.net-mvc-5 dropdownlistfor


    【解决方案1】:

    http://www.asp.net/mvc/overview/releases/mvc51-release-notes

    安装 MVC 5.1 并使用 @Html.EnumDropDownListFor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2011-07-01
      • 2014-04-04
      相关资源
      最近更新 更多