枚举类型MVC Razor的复选框列表

本文关键字:复选框 列表 Razor 类型 MVC 枚举 | 更新日期: 2023-09-27 18:26:42

在我的c#.net MVC应用程序中,我想显示枚举类型的复选框列表。

我有一个枚举类型

[Flags]
public enum ModeType
{
Undefined = 0,
Read= 1,
Edit= 2
  }

我的型号是

Public TrainingModel
   {
         public int UserID {get;set;}
         public ModeType Type {get;set}
   }

在我看来,我需要两个复选框,一个用于读取,另一个用于编辑所以我尝试了

    @Html.CheckBoxFor(m => m.Type== ModeType.Read)
@Html.CheckBoxFor(m => m.Type== ModeType.Edit)

但这给了我一个错误模板只能与字段访问、属性访问、一维数组索引或单参数自定义索引器表达式一起使用。

我通过在我的模型中添加两个属性来解决这个问题

 Public TrainingModel
   {
         public int UserID {get;set;}
         public ModeType Type {get;set}
         public bool IsRead
         {
           get{Type.HasFlag(ModeType.Read);}
           set{Type |=ModeType.Read;}
         }
         public bool IsEdit
         {
           get{Type.HasFlag(ModeType.Edit);}
           set{Type |=ModeType.Edit;}
         }
   }

然后使我的视图

@Html.CheckboxFor(m => m.IsRead)
@Html.CheckboxFor(m => m.IsEdit)

我知道我处理这个问题的方式是不正确的,应该有更好的方法来实现这一点。有人能给我这个建议吗。

枚举类型MVC Razor的复选框列表

以下是我如何将枚举转换为选择列表。Enum.cshtml(一个编辑器模板,带有指向它的UI提示):

@model Enum
@Html.DropDownListFor(model => model, Model.ToSelectList(), "Select")

然后在视图中使用的Extension方法:

    /// <summary>
    /// Gets a select list from an enum.
    /// </summary>
    /// <param name="enumObject">The enum object.</param>
    /// <returns></returns>
    public static SelectList ToSelectList(this Enum enumObject)
    {
        List<KeyValuePair<string, string>> selectListItemList = null;
        SelectList selectList = null;
        try
        {
            // Cast the enum values to strings then linq them into a key value pair we can use for the select list.
            selectListItemList = Enum.GetNames(enumObject.GetType()).Cast<string>().Select(item => { return new KeyValuePair<string, string>(item, item.PascalCaseToReadableString()); }).ToList();
            // Remove default value of Enum. This is handled in the editor template with the optionLabel argument.
            selectListItemList.Remove(new KeyValuePair<string, string>("None", "None"));
            // Build the select list from it.
            selectList = new SelectList(selectListItemList, "key", "value", enumObject);
        }
        catch (Exception exception)
        {
            Functions.LogError(exception);
        }
        return selectList;
    }

要将此解决方案重构为复选框列表,您可以简单地从函数传递回键值对,并在编辑器模板中循环使用它们。

我希望这能有所帮助。