ASP.NET MVC - Passing a Flag Enum to an Action as Parameter

A flag Enum is an Enumeration that can hold multiple values per instance An example of such Enum is:

public enum enDays
    None = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 4,
    Thursday = 8,
    Friday = 16,
    Saturday = 32,
    Sunday = 64

And we could use it like this:

enDays days = enDays.Monday | enDays.Friday;

So our “days” field would have both Monday and Friday

If we want to create a controller and inside it an action that takes as an input the following enum we would write something like:

public partial class HomeController
    public virtual ActionResult DoSomething(enDays days)

Then we could navigate to /Home/DoSomething?days=Monday and give value enDays.Monday to “days” argument.

But if we write /Home/DoSomething?days=Monday,Friday it’s the same as enDays.Monday | enDays.Friday!

We can also write /Home/DoSomething?days=17 which is the same as above!

Comma-separated Enum values or the equivalent numeric value, your choice!



  • Dostava Hrane on said


Dostava Hrane

    Very helpful. I have to try this.



    This isn't working for me. I got an error stating that ref type parameters need to be nullable or set up defined as optional.
    $1Next, I tried defining the parameter as optional in my routing rules -- and got the same error.
    $1Finally, I tried defining the parameter as nullable e.g., public virtual ActionResult DoSomething(enDays? days) -- this time, no error, but the parameter value is always null regardless of what is passed.
    $1Could you post your routing rule? I suspect I may missing something there. Thanks.



    @pj I tried all those cases using a nullable, or an optional parameter and it works. I am using ASP.NET MVC3. I don't know if this is working in previous versions. I did my tests in a new project with default configuration.

Add a Comment (gravatar-enabled)