Yes i would also suggest an enum in this scenario.
Here is how you can do it in ASP.NET MVC:
Your enum should look like this (see the link you provided):
[Flags]
public enum Days
{
Sunday = 0x1,
Monday = 0x2,
Tuesday = 0x4,
Wednesday = 0x8,
Thursday = 0x10,
Friday = 0x20,
Saturday = 0x40
}
For reusability purposes I have created an generic html helper that looks like this:
public static IHtmlString CheckboxListForEnum<T>(this HtmlHelper html, string name, T modelItems) where T : struct
{
StringBuilder sb = new StringBuilder();
foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())
{
TagBuilder builder = new TagBuilder("input");
long targetValue = Convert.ToInt64(item);
long flagValue = Convert.ToInt64(modelItems);
if ((targetValue & flagValue) == targetValue)
builder.MergeAttribute("checked", "checked");
builder.MergeAttribute("type", "checkbox");
builder.MergeAttribute("value", item.ToString());
builder.MergeAttribute("name", name);
builder.InnerHtml = item.ToString();
sb.Append(builder.ToString(TagRenderMode.Normal));
}
return new HtmlString(sb.ToString());
}
You can use the same html helper for all enumeration types.
Usage:
Now for demonstration purposes let say that you have a model like this:
Model:
public class TVShow
{
public string Title { get; set; }
public string Description { get; set; }
public Days AvailableOn { get; set; }
}
Controller Action:
public ActionResult Show()
{
var show = new TVShow
{
Title = "Late Late Show",
AvailableOn = Days.Monday | Days.Friday
};
return View(show);
}
View (strongly typed):
<%: Model.Title %>
<%: Model.Description %>
<%: Html.CheckboxListForEnum<Days>("days", Model.AvailableOn)%>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…