2

原谅我的无知。没有做很多 MVC 工作,我确信一定有更好的方法来做到这一点,但我似乎找不到它。我有一个这样的标志枚举:

[Flags]
public enum Services
{
    Foo = 1,
    Bar = 2,
    Meh = 4
}

我的模型上的 SelectedServices 属性具有此类型的值。在视图中,我为每个可能的服务设置了一个复选框。我已经像这样实现了绑定逻辑:

<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 中的相关概念是什么?

4

2 回答 2

4

当您提交表单时,您当前的代码不会绑定到您的代码,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
于 2016-06-23T12:17:32.387 回答
2

创建剃须刀助手:

@helper DisplayFlagHelper(Services flag)
{
   <div><label><input type="checkbox" name="services" value="@((int)flag)" 
   if(Model.SelectedServices.HasFlag(flag))
   {
       <text>checked</text>
   }
    />@flag</label></div>
}

@DisplayFlagHelper(Services.Foo)

或共享视图

于 2016-06-23T11:55:38.727 回答