一般に、ビューモデルを設計するときに列挙型を使用することは避けています。これは、列挙型がASP.NETMVCのヘルパーやすぐに使用できるモデルバインダーで機能しないためです。ドメインモデルでは完全に問題ありませんが、ビューモデルでは他のタイプを使用できます。そのため、ドメインモデルとビューモデルの間を行ったり来たりするマッピングレイヤーを離れて、それらの変換について心配します。
そうは言っても、何らかの理由でこの状況で列挙型を使用することにした場合は、カスタムモデルバインダーをロールすることができます。
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());
}
これにより、より良い結果が得られます。
