使用Flags枚举时如何减少ASP.NET MVC视图中的代码重复
原谅我的无知。 没有做过很多MVC的工作,我确信必须有更好的方法来做到这一点,但我似乎无法找到它。 我有一个像这样的Flags枚举:
[Flags] public enum Services { Foo = 1, Bar = 2, Meh = 4 }
我的Model上的SelectedServices属性具有此类型的值。 在视图中,我为每个可能的服务都有一个复选框。 我已经像这样实现了绑定逻辑:
等等。 哪个有效,但真的非常混乱。
肯定有更好的方法来封装它 – 但我不知道MVC中的相关概念是什么?
创建剃刀助手:
@helper DisplayFlagHelper(Services flag) { }
@DisplayFlagHelper(Services.Foo)
或共享视图
当您提交表单时,您当前的代码不会绑定到您的enum
,因为它只会作为值数组接收。 与往常一样,使用视图模型来表示要在视图中显示/编辑的内容。
public class MyViewModel { [Display(Name = "Foo")] public bool IsFoo { get; set; } [Display(Name = "Bar")] public bool IsBar { get; set; } [Display(Name = "Meh")] public bool IsMeh { get; set; } .... // other properties of your view model }
并将enum
值映射到视图模型
model.IsFoo= yourEnumProperty.HasFlag(Type.Foo); // etc
并在视图中
@model MyViewModel .... @Html.CheckBoxFor(m => m.IsFoo) @Html.LabelFor(m => m.IsFoo) @Html.CheckBoxFor(m => m.IsBar) @Html.LabelFor(m => m.IsBar) ....
最后在POST方法中
[HttpPost] public ActionResult Edit(MyViewModel model) { bool isTypeValid = model.IsFoo || model.IsBar || model.IsMeh; if (!isTypeValid) { // add a ModelState error and return the view } Services myEnumValue = model.IsFoo ? Services.Foo : 0; myEnumValue |= model.IsBar ? Services.Bar : 0; myEnumValue |= model.IsMeh ? Services.Meh : 0; // map the view model to an instance of the data model, save and redirect