【问题标题】:Why enum values with Enum.GetValues(typeof()) are not recognized if they are declared in Model?如果 Enum.GetValues(typeof()) 的枚举值在 Model 中声明,为什么无法识别它们?
【发布时间】:2019-05-20 10:44:05
【问题描述】:

我想在 MVC 中使用枚举填充性别值的下拉列表,但 Enum.GetValues(typeof(...) 没有返回值。这是 .cshtml 部分:

    <div class="form-group">
        @Html.LabelFor(m => m.parGender, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.parGender, new SelectList(Enum.GetValues(typeof(Gender))), new { @class = "form-control" })
        </div>
    </div>

这是这个模型的模型:

        [Required(ErrorMessage = "Select your gender!")]
        [Display(Name = "Gender:")]
        public Gender parGender { get; set; }

        public enum Gender
        {
            Male,
            Female
        }

我错过了什么?

【问题讨论】:

  • 不相关的注释...“性别”可能不是枚举的好选择,尤其是具有两个固定选项的枚举;除非您处于非常特定的环境中,否则这种选择往往不会很好地结束

标签: c# asp.net-mvc enums model


【解决方案1】:

您需要将结果转换为您想要的实际数组类型

(Gender[])Enum.GetValues(typeof(Gender))

【讨论】:

    【解决方案2】:

    您将必须投射它,然后可能选择正确的类型 - 我已将它用于 Kendo Dropdowns,不确定它是否完全相同:

    Enum.GetValues(typeof(Gender)).Cast<Gender>().Select(at =>
        new SelectListItem
        {
            Text = at.ToString(),
            Value = ((int)at).ToString()
        }
    ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多