How to iterate through an enumeration of flags and create checkboxes that are checked appropriately for each value?

StackOverflow https://stackoverflow.com/questions/19056547

Question

I have an Enum of flags to represent the days of the week, with a few extra values that indicate weekdays, weekends, every day, or no days.

Here's the Enum:

[Flags]
public enum DayOfWeek : short
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64,
    Weekday = 62,
    Weekend = 65,
    Everyday = 127,
    None = 0
}

I also have a View Model with a property, DayOfWeek with a type of DayOfWeek.

In my View, I need to create a checkbox for each day of the week and somehow appropriately check the boxes based on which days have been saved.

How can I do this?

Était-ce utile?

La solution

I found a good solution.

Here's what I came up with:

@foreach (DayOfWeek item in Enum.GetValues(typeof(DayOfWeek)))
{
    if (0 < item && (item <= DayOfWeek.Friday || item == DayOfWeek.Saturday))
    {
        @Html.Label("DayOfWeek", item.ToString())
        @Html.CheckBox("DayOfWeek", (Model.DayOfWeek.HasFlag(item)), new { value = item })
    }
}

The conditional statement within the loop is to ensure that only the actual days get displayed.

This works for my purposes, and the concept can be easily applied to other Enumerations. Specific implementation will need some changes, but you get the idea.

Autres conseils

You can iterate through your Enum like this:

foreach (var val in typeof(DayOfWeek).GetEnumNames())
               ....

Also you can Pars and convert back a string to your Enum

var day = Enum.Parse(typeof(DayOfWeek) , yourString);

yourstring can be anything you want for example the name of the checkbox.

I don't know more about your problem and your project architecture, it's up to you to adapt these options to your problem.I hope this helps.

It's a fairly manual process... To check if Sunday is selected, for example:

bool isSunday = (dayOfWeekEnum & DayOfWeek.Sunday) == DayOfWeek.Sunday;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top