代码之家  ›  专栏  ›  技术社区  ›  Csh

枚举没有在Asp.net中填充正确的选项

  •  0
  • Csh  · 技术社区  · 2 年前

    我是ASP的新手。NET和我面临的一个问题是,当我将枚举填充为列表时,它会设置一个默认值,并且不会显示 <option> 标记作为开始,它只显示为其中一个选项。

    在里面 .cshtml 文件

    <label asp-for="Type" class="control-label">enum list</label>
    <select class="form-select"asp-for="Type" asp items="Html.GetEnumSelectList<Type>()" oninput="this.className = 'form-select'">
        <option value="">select pls</option>
    </select>
    <span asp-validation-for="Type" class="text-danger"></span>
    

    它显示为

    enter image description here

    我想让它显示的是这样的选项标签

    enter image description here

    这是枚举:

    public enum Type
    {
        [Display(Name = "New")]
        New,
        [Display(Name = "Reorder")]
        Reorder
    }
    

    我在这样的模型类中使用它:

    public class Model1
    {
        // other fields
        [Column(TypeName = "nvarchar(24)")]
        [Required]
        public Type Type { get; set; }
        //others
    }
    

    查看模型类:

    public class VM
    {
        // others
        public Type Type { get; set; }
        public Model1 Model1{ get; set; }
        // others
    }
    

    在里面 MyController 操作方法,我分配了的值 Model1 到视图中使用的视图模型:

        // GET: type/Create
        public IActionResult Create()
        {
            VM modelVM = new VM()
                {
                    Model1= new Model1()
                };
    
            return View(modelVM);
        }
    

    我试着用 SelectListItem 但它仍然存在同样的问题。

    我使用多种语言,所以 [Display(Name = "")] 对于翻译来说很重要,但不起作用 选择列表项 。

    非常感谢。

    1 回复  |  直到 2 年前
        1
  •  0
  •   poke    2 年前

    请尝试将视图模型属性设置为null:

    public class VM
    {
        public Type? Type { get; set; }
    }
    

    否则,不可为null的枚举类型的属性将使用您的枚举的默认值初始化,该值是第一个枚举成员, Type.New 。而且因为 Type 属性有一个值,它将用于选择的默认值 <select> 。

    但是,如果该属性可以为null,则该属性的值为 null 所以 <选择> 不会默认为枚举中的值,而是使用显示第一个选项 value="" 相反