原谅我的无知。没有完成很多 MVC 工作,我相信一定有更好的方法来做到这一点,但我似乎找不到它。我有一个像这样的 Flags 枚举:
[Flags]
public enum Services
{
Foo = 1,
Bar = 2,
Meh = 4
}
我的模型上的 SelectedServices 属性具有此类型的值。在 View 中,我为每个可能的服务都有一个复选框。我已经像这样实现了绑定(bind)逻辑:
<div><label><input type="checkbox" name="services" value="@((int)Services.Foo)"
@if(Model.SelectedServices.HasFlag(Services.Foo))
{
<text>checked</text>
}
/>Foo</label></div>
<div><label><input type="checkbox" name="services" value="@((int)Services.Bar)"
@if(Model.SelectedServices.HasFlag(Services.Bar))
{
<text>checked</text>
}
/>Bar</label></div>
等等。哪个有效,但真的非常困惑。
肯定有更好的方法来封装它 - 但我不知道 MVC 中的相关概念是什么?
最佳答案
当您提交表单时,您当前的代码不会绑定(bind)到您的 enum
,因为它只会作为值数组接收。与往常一样,使用 View 模型来表示您要在 View 中显示/编辑的内容。
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
}
并将枚举
值映射到 View 模型
model.IsFoo= yourEnumProperty.HasFlag(Type.Foo); // etc
在 View 中
@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
关于c# - 使用 Flags 枚举时如何减少 ASP.NET MVC View 中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37990786/