C# 枚举类型MVC Razor的复选框列表
在我的c.NETMVC应用程序中,我想显示枚举类型的复选框列表 我有一个枚举类型C# 枚举类型MVC Razor的复选框列表,c#,asp.net-mvc,razorgenerator,C#,Asp.net Mvc,Razorgenerator,在我的c.NETMVC应用程序中,我想显示枚举类型的复选框列表 我有一个枚举类型 [Flags] public enum ModeType { Undefined = 0, Read= 1, Edit= 2 } 我的模型是 Public TrainingModel { public int UserID {get;set;} public ModeType Type {get;set} } 在我看来,我需要两个复选框,一个用于读取,另一个用
[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)
我知道我的方法是不正确的,应该有更好的方法来实现这一点。
有人能给我一些建议吗。下面是我如何解决这个问题,将枚举转换为选择列表。Enum.cshtml是一个编辑器模板,带有指向该模板的UI提示:
@model Enum
@Html.DropDownListFor(model => model, Model.ToSelectList(), "Select")
然后,视图中使用的扩展方法:
/// <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;
}
要将此解决方案重构为复选框列表,只需从函数传回键值对,并在编辑器模板中循环它们
我希望这能有所帮助。除了缺少ViewModel之外,我看不到更好的方法。HTML本身不会处理只剩下两个选项的标志复选框:您所做的是将复选框分开处理服务器端,并使用javascript管理未映射的复选框和映射的隐藏输入添加选定的标志值并设置该输入。在这两个选项中,您的更干净。javascript的唯一优势是减少了POST数据。@Pluc感谢您的回复。但这是否意味着,如果我要向我的枚举类型添加更多模式,那么我也必须添加属性。是的,它会。我想您也可以破解一些东西,迭代枚举中的每个选项并生成复选框,然后从未绑定到模型的表单结果中收集响应,将它们相加并将结果保存到模型中。它不会那么干净,但会随着枚举更改而扩展。但老实说,如果您计划添加枚举选项,您可能希望选择它们在视图中的显示顺序,并且当您触摸视图时,在视图中更改它并不难: