2

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?

4

3 回答 3

7

我找到了一个很好的解决方案。

这是我想出的:

@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 })
    }
}

循环中的条件语句是为了确保只显示实际天数。

这适用于我的目的,并且该概念可以很容易地应用于其他枚举。具体实现将需要一些更改,但你明白了。

于 2013-09-27T17:33:41.707 回答
0

你可以Enum像这样迭代你:

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

您也可以Pars将 a 转换回string您的Enum

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

yourstring可以是任何你想要的东西,例如checkbox.

我不知道更多关于您的问题和项目架构的信息,您可以根据自己的问题调整这些选项。我希望这会有所帮助。

于 2013-09-27T17:31:53.410 回答
-1

这是一个相当手动的过程...检查是否选择了星期日,例如:

bool isSunday = (dayOfWeekEnum & DayOfWeek.Sunday) == DayOfWeek.Sunday;
于 2013-09-27T17:32:01.270 回答