A previous developer (who no longer works with us, so I can't ask him) has done something pretty slick, that I really do not understand. We have this enum:
[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
}
In the database, SidingTypes
is stored as a single int, which is a sum of all the values selected.
In the Model:
public SidingTypePreference? SidingTypes { get; set; }
In the controller, where table
is just a row result from a query:
Model.SidingTypes = table.SidingTypes
And in the view:
@Html.EditorFor(m => Model.SidingTypes, new { @class = "form-control input-sm", GroupID = "SidingTypePreference", Cols = 1 })
But, here's the part I don't understand. Let's say that SidingTypes = 10
. By some sort of voodoo magic, that int is translated into:
<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
(class redacted just to prevent the need to scroll, but they are all 'lookup-checkbox-SidingTypes'.)
From the value of that int, it knows which are checked and which are not.
FIRST QUESTION: Is this native .NET? Or is there some extension method or template that I need to find?
SECOND QUESTION: What I need to do, independent of anything else, is to build a method to determine if an enum is selected.
Something like:
private bool IsSelected(int SidingTypes, SidingTypePreference sidingTypePreference)
{
... ?? ...
return true or false;
}