Search code examples
c#asp.net-mvcenumsenum-flags

How to reduce code duplication in ASP.NET MVC view when working with Flags enum


Forgive my ignorance. Not done a lot of MVC work, and I'm sure there must be a better way to do this but I can't seem to find it. I have a Flags enum like this:

[Flags]
public enum Services
{
    Foo = 1,
    Bar = 2,
    Meh = 4
}

And a SelectedServices property on my Model which has a value of this type. In the View, I have a checkbox for each possible service. I have implemented the binding logic like so:

<div><label><input type="checkbox" name="services" value="@((int)Services.Foo)" 
@if(Model.SelectedServices.HasFlag(Services.Foo))
{
    <text>checked</text>
}
 />Foo</label></div>

<div><label><input type="checkbox" name="services" value="@((int)Services.Bar)" 
@if(Model.SelectedServices.HasFlag(Services.Bar))
{
    <text>checked</text>
}
 />Bar</label></div>

And so on. Which works, but is really horribly messy.

There must, surely be a better way to encapsulate this - but I have no idea what the relevant concept is in MVC?


Solution

  • Create razor helper :

    @helper DisplayFlagHelper(Services flag)
    {
       <div><label><input type="checkbox" name="services" value="@((int)flag)" 
       if(Model.SelectedServices.HasFlag(flag))
       {
           <text>checked</text>
       }
        />@flag</label></div>
    }
    

    @DisplayFlagHelper(Services.Foo)

    or shared view