【发布时间】:2017-02-01 19:14:23
【问题描述】:
以前的开发人员(他不再与我们合作,所以我不能问他)做了一些非常巧妙的事情,我真的不明白。我们有这个枚举:
[Flags]
public enum SidingTypePreference
{
[Value(Name = "Vinyl")]
Vinyl = 1,
[Value(Name = "Metal or Aluminum")]
MetalOrAluminum = 2,
[Value(Name = "Composite")]
Composite = 4,
[Value(Name = "Wood")]
Wood = 8,
[Value(Name = "Other")]
Other = 16
}
在数据库中,SidingTypes 存储为单个 int,它是所有选定值的总和。
在模型中:
public SidingTypePreference? SidingTypes { get; set; }
在控制器中,table 只是查询的一行结果:
Model.SidingTypes = table.SidingTypes
在视图中:
@Html.EditorFor(m => Model.SidingTypes, new { @class = "form-control input-sm", GroupID = "SidingTypePreference", Cols = 1 })
但是,这是我不明白的部分。假设SidingTypes = 10。通过某种巫术魔法,该 int 被翻译成:
<input type="checkbox" class="..." name="SidingTypes_0" value="1"> Vinyl
<input type="checkbox" class="..." name="SidingTypes_1" value="2" checked> Metal or Aluminum
<input type="checkbox" class="..." name="SidingTypes_2" value="4"> Composite
<input type="checkbox" class="..." name="SidingTypes_3" value="8" checked> Wood
<input type="checkbox" class="..." name="SidingTypes_4" value="16"> Other
(编辑类只是为了防止需要滚动,但它们都是'lookup-checkbox-SidingTypes'。)
根据该 int 的值,它知道哪些已检查,哪些未检查。
第一个问题:这是本机 .NET 吗?或者我需要找到一些扩展方法或模板吗?
第二个问题:我需要做的,独立于其他任何事情,是构建一个方法来确定是否选择了枚举。
类似:
private bool IsSelected(int SidingTypes, SidingTypePreference sidingTypePreference)
{
... ?? ...
return true or false;
}
【问题讨论】:
-
嗯,具有
Flags属性的枚举将一个值分解为构成该复合值的等效位(例如10 = 2 + 8)我怀疑项目中有一个自定义模板可以转换将枚举值放入一组复选框中。 -
看看这个:msdn.microsoft.com/en-us/library/… 这个帖子也有一个很好的答案:stackoverflow.com/questions/8447/…
-
请参阅 this answer 以使用具有
[Flags]属性的枚举
标签: c# .net asp.net-mvc enums