0

I've seen ways of using HTML Helpers and such to deal with enums in MVC. I've taken a different approach in that I pass a string[] of the checked boxes back to the controller. I am doing this:

            foreach (string svf in property.SiteVisibilityFlags)
            {                                     
                Enums.SiteVisibilityFlags flagTester;
                if (Enum.TryParse<Enums.SiteVisibilityFlags>(svf, out flagTester))
                {
                    // add to domainProperty
                    domainProperty.SiteVisibilityFlags = flagTester; <--Here is where I mean
                }
            }

Now, I know that normally, with a flagged enum you do something like:

     domainProperty.SiteVisibilityFlags = Enums.SiteVisibilityFlags.Corporate | Enums.SiteVisibilityFlags.Properties;

So, if/how can I accomplish the '|'... in this methodology?

Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56
  • you are trying to cast the strings back to enum ... so what's the problem.. could you clarify a bit.. – noobed May 05 '15 at 18:00

2 Answers2

1

You could use the [FlagAttribute] explained here. From there you can simply use the bit-or (|) operator as follows

domainProperty.SiteVisibilityFlags |= flagTester;

Also there is a really good explanation with examples on stackoverflow about attribute

Community
  • 1
  • 1
noobed
  • 1,329
  • 11
  • 24
1

figured it out. Any enum that has [Flags] as an attribute can be solved by summing up the values of all checked items like this:

// Site Visibility Flags        
            int SiteVisibilityTotalValue = 0;
            foreach (string svf in property.SiteVisibilityFlags)
            {
                Enums.SiteVisibilityFlags flagTester;
                if (Enum.TryParse<Enums.SiteVisibilityFlags>(svf, out flagTester))
                {
                    // sum up values to get total to them convert to enum
                    SiteVisibilityTotalValue += (int)flagTester;
                }
            }
            // convert total to Enum
            domainProperty.SiteVisibilityFlags = (Enums.SiteVisibilityFlags)SiteVisibilityTotalValue;
Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56