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!
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:
which will be registered in Application_Start:
So far so good. Now the standard stuff:
View model:
Controller:
View (
~/Views/Home/Index.cshtml):custom editor template for the
NotificationDeliveryType(~/Views/Shared/EditorTemplates/NotificationDeliveryType.cshtml):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:
and we clean the mess in our editor template:
which yields the table:
Now obviously it would have been nice if we could provide friendlier labels for those checkboxes. Like for example:
All we have to do is adapt the HTML helper we wrote earlier:
which gives us a better result: