Search code examples
model-view-controllerenumsenum-flags

MVC enum flags: Why is the first enum value always true?


So, I have a flagged enum:

 [Flags]
 public enum SiteVisibilityFlags : short
 {
     None = 0,
     Corporate = 1,
     Properties = 2,
     Kiosk = 4
 }

Problem is, whatever I set it too, 'None' is always true... no matter what. say I set it like this:

..., SiteVisibilityFlags = Enums.SiteVisibilityFlags.Corporate  ...

Then try to view it:

<dd>
        @foreach (Enums.SiteVisibilityFlags svf in Enum.GetValues(typeof(Enums.SiteVisibilityFlags)))
        {
            @Html.CheckBox("SiteVisibilityFlags", (Model.SiteVisibilityFlags.HasFlag(svf)), new { value = svf, disabled = "disabled" })
            @Html.Label("SiteVisibilityFlagsLabel", svf.ToString())
            @:&nbsp;
        }
    </dd>

Here, Model.SiteVisibilityFlags.HasFlag(svf) is ALWAYS true for 'None', and it shouldn't be. Verified in the db, the value is '1'... but None is still checked. I've tried every permutation of single and combinations of Corporate, Properties, and Kiosk, the checkboxes work as expected, checking and unchecking according to the flag value, but 'None' is always checked/true.

What am I missing?


Solution

  • According to this article Flagged Enums should start with '1' not '0' because it causes issues.