一般来说,我在设计我的视图模型时避免使用枚举,因为它们不使用 ASP.NET MVC 的助手和开箱即用的模型绑定器。它们在您的域模型中非常好,但对于视图模型,您可以使用其他类型。所以我离开了负责在我的域模型和视图模型之间来回转换的映射层来担心这些转换。
话虽如此,如果由于某种原因您决定在这种情况下使用枚举,您可以滚动自定义模型绑定器:
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);
}
}
这将在 Application_Start 中注册:
ModelBinders.Binders.Add(
typeof(NotificationDeliveryType),
new NotificationDeliveryTypeModelBinder()
);
到目前为止,一切都很好。现在标准的东西:
查看型号:
[Flags]
public enum NotificationDeliveryType
{
InSystem = 1,
Email = 2,
Text = 4
}
public class MyViewModel
{
public IEnumerable<NotificationDeliveryType> Notifications { get; set; }
}
控制器:
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);
}
}
查看 ( ~/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>
}
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>
很明显,在编辑器模板中编写此类代码的软件开发人员(在本例中为我)不应该为自己的工作感到非常自豪。我的意思是看它!即使是我在 5 分钟前写了这个 Razor 模板也无法理解它的作用。
所以我们在一个可重用的自定义 HTML 帮助器中重构了这个意大利面条代码:
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());
}
}
然后我们清理编辑器模板中的混乱:
@model NotificationDeliveryType
<tr>
<td>
@Html.CheckBoxesForEnumModel()
</td>
</tr>
这产生了表格:

现在显然,如果我们可以为这些复选框提供更友好的标签,那就太好了。例如:
[Flags]
public enum NotificationDeliveryType
{
[Display(Name = "in da system")]
InSystem = 1,
[Display(Name = "@")]
Email = 2,
[Display(Name = "txt")]
Text = 4
}
我们所要做的就是调整我们之前编写的 HTML 助手:
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());
}
这给了我们一个更好的结果:
