从EnumDropDownListFor中删除空条目

问题描述 投票:0回答:1

我想从我的EnumDropDownList中删除Blank / Empty条目 - 已在线搜索并尝试下面的链接但似乎没有任何工作

Remove blank/empty entry at top of EnumDropDownListFor box

Remove blank entry from EnumDropDownListFor(...)?

代码: -

<td>
@Html.EnumDropDownListFor(model => model.Actions, new { @id = "actions", @class = "form-control" })
</td>

型号代码: -

[Required]
    [Range(1, int.MaxValue, ErrorMessage = "Select an Action")]
    [Display(Name = "Actions")]
    public ItemTypes Actions { get; set; }

控制器中的枚举: -

 public enum ItemTypes
    {
        Add = 1,
        Remove = 2
    }

下拉呈现如下: -

enter image description here

asp.net-mvc model-view-controller enums html-helper
1个回答
2
投票

听起来你的问题是用起始索引1定义的枚举:

public enum ItemTypes
{
    Add = 1,
    Remove = 2
}

由于没有枚举器在上面的enum中指定了索引0,因此帮助器在SelectListItem集合列表中包含零索引,因此显示为默认选择项的空选项(请记住,枚举和集合都使用从零开始的索引,因此第一项具有索引零)。

您可以定义一个索引为0的枚举器来设置默认选择值:

public enum ItemTypes
{
    Nothing = 0,
    Add = 1,
    Remove = 2
}

或者使用标准的DropDownListFor帮助器,使用SelectListItem定义的其他属性来绑定枚举值:

模型

public List<SelectListItem> ActionList { get; set; }

调节器

ActionList = Enum.GetNames(typeof(ItemTypes)).Select(x => new SelectListItem { Text = x, Value = x }).ToList();

视图

@Html.DropDownListFor(model => model.Actions, Model.ActionList, new { @id = "actions", @class = "form-control" })

参考:

C# Enumeration Types (MS Docs)

© www.soinside.com 2019 - 2024. All rights reserved.