2

私の無知を許してください。多くの MVC 作業を行っていません。これを行うためのより良い方法があるに違いないと確信していますが、それを見つけることができないようです。次のような Flags 列挙型があります。

[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 に答える