Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7516923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T01:17:13+00:00 2026-05-30T01:17:13+00:00

I have a grid of Enum Flags in which each record is a row

  • 0

I have a grid of Enum Flags in which each record is a row of checkboxes to determine that record’s flag values. This is a list of notifications that the system offers and the user can pick (for each one) how they want them delivered:

[Flag]
public enum NotificationDeliveryType
{
  InSystem = 1,
  Email = 2,
  Text = 4
}

I found this article but he’s getting back a single flag value and he’s binding it in the controller like this (with a days of the week concept):

[HttpPost]
public ActionResult MyPostedPage(MyModel model)
{
  //I moved the logic for setting this into a helper 
  //because this could be re-used elsewhere.
  model.WeekDays = Enum<DayOfWeek>.ParseToEnumFlag(Request.Form, "WeekDays[]");
  ...
}

I can’t find anywhere that the MVC 3 model binder can handle flags. Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T01:17:14+00:00Added an answer on May 30, 2026 at 1:17 am

    In general I avoid using enums when designing my view models because they don’t play with ASP.NET MVC’s helpers and out of the box model binder. They are perfectly fine in your domain models but for view models you could use other types. So I leave my mapping layer which is responsible to convert back and forth between my domain models and view models to worry about those conversions.

    This being said, if for some reason you decide to use enums in this situation you could roll a custom model binder:

    public class NotificationDeliveryTypeModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value != null )
            {
                var rawValues = value.RawValue as string[];
                if (rawValues != null)
                {
                    NotificationDeliveryType result;
                    if (Enum.TryParse<NotificationDeliveryType>(string.Join(",", rawValues), out result))
                    {
                        return result;
                    }
                }
            }
            return base.BindModel(controllerContext, bindingContext);
        }
    }
    

    which will be registered in Application_Start:

    ModelBinders.Binders.Add(
        typeof(NotificationDeliveryType), 
        new NotificationDeliveryTypeModelBinder()
    );
    

    So far so good. Now the standard stuff:

    View model:

    [Flags]
    public enum NotificationDeliveryType
    {
        InSystem = 1,
        Email = 2,
        Text = 4
    }
    
    public class MyViewModel
    {
        public IEnumerable<NotificationDeliveryType> Notifications { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyViewModel
            {
                Notifications = new[]
                {
                    NotificationDeliveryType.Email,
                    NotificationDeliveryType.InSystem | NotificationDeliveryType.Text
                }
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    View (~/Views/Home/Index.cshtml):

    @model MyViewModel
    @using (Html.BeginForm())
    {
        <table>
            <thead>
                <tr>
                    <th>Notification</th>
                </tr>
            </thead>
            <tbody>
                @Html.EditorFor(x => x.Notifications)
            </tbody>
        </table>
        <button type="submit">OK</button>
    }
    

    custom editor template for the NotificationDeliveryType (~/Views/Shared/EditorTemplates/NotificationDeliveryType.cshtml):

    @model NotificationDeliveryType
    
    <tr>
        <td>
            @foreach (NotificationDeliveryType item in Enum.GetValues(typeof(NotificationDeliveryType)))
            {
                <label for="@ViewData.TemplateInfo.GetFullHtmlFieldId(item.ToString())">@item</label>
                <input type="checkbox" id="@ViewData.TemplateInfo.GetFullHtmlFieldId(item.ToString())" name="@(ViewData.TemplateInfo.GetFullHtmlFieldName(""))" value="@item" @Html.Raw((Model & item) == item ? "checked=\"checked\"" : "") />
            }
        </td>
    </tr>
    

    It’s obvious that a software developer (me in this case) writing such code in an editor template shouldn’t be very proud of his work. I mean look t it! Even I that wrote this Razor template like 5 minutes ago can no longer understand what it does.

    So we refactor this spaghetti code in a reusable custom HTML helper:

    public static class HtmlExtensions
    {
        public static IHtmlString CheckBoxesForEnumModel<TModel>(this HtmlHelper<TModel> htmlHelper)
        {
            if (!typeof(TModel).IsEnum)
            {
                throw new ArgumentException("this helper can only be used with enums");
            }
            var sb = new StringBuilder();
            foreach (Enum item in Enum.GetValues(typeof(TModel)))
            {
                var ti = htmlHelper.ViewData.TemplateInfo;
                var id = ti.GetFullHtmlFieldId(item.ToString());
                var name = ti.GetFullHtmlFieldName(string.Empty);
                var label = new TagBuilder("label");
                label.Attributes["for"] = id;
                label.SetInnerText(item.ToString());
                sb.AppendLine(label.ToString());
    
                var checkbox = new TagBuilder("input");
                checkbox.Attributes["id"] = id;
                checkbox.Attributes["name"] = name;
                checkbox.Attributes["type"] = "checkbox";
                checkbox.Attributes["value"] = item.ToString();
                var model = htmlHelper.ViewData.Model as Enum;
                if (model.HasFlag(item))
                {
                    checkbox.Attributes["checked"] = "checked";
                }
                sb.AppendLine(checkbox.ToString());
            }
    
            return new HtmlString(sb.ToString());
        }
    }
    

    and we clean the mess in our editor template:

    @model NotificationDeliveryType
    <tr>
        <td>
            @Html.CheckBoxesForEnumModel()
        </td>
    </tr>
    

    which yields the table:

    enter image description here

    Now obviously it would have been nice if we could provide friendlier labels for those checkboxes. Like for example:

    [Flags]
    public enum NotificationDeliveryType
    {
        [Display(Name = "in da system")]
        InSystem = 1,
    
        [Display(Name = "@")]
        Email = 2,
    
        [Display(Name = "txt")]
        Text = 4
    }
    

    All we have to do is adapt the HTML helper we wrote earlier:

    var field = item.GetType().GetField(item.ToString());
    var display = field
        .GetCustomAttributes(typeof(DisplayAttribute), true)
        .FirstOrDefault() as DisplayAttribute;
    if (display != null)
    {
        label.SetInnerText(display.Name);
    }
    else
    {
        label.SetInnerText(item.ToString());
    }
    

    which gives us a better result:

    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Grid inside a Canvas defined like this: <Canvas x:Name=outerCanvas> <Grid Grid.Row=1
Hai presently i have grid like this. <Grid Name=tGrid1 Grid.Row=0 Background=Black > </Grid> <Grid
I have grid view which contains five radio buttons per row. Out of these
I have a grid that is declared like: PlayerStatus enum { OCCUPIED, VACANT }
I have grid that has a list of about 16 documents that can change
I have a grid and I need to dynamically replace a control that resides
I have a grid that has multiple rows. I want to hide/show one of
I have a grid in a XAML file in a WPF project. This MainGrid
I have a grid bound to a BindingSource which is bound to DataContext table,
I have a grid, which I want to add a button at the top

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.