首页 > 解决方案 > 如果 Enum.GetValues(typeof()) 的枚举值在 Model 中声明,为什么无法识别它们?

问题描述

我想在 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-mvcenumsmodel

解决方案


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

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

推荐阅读