Asp.net-Mvc

ASP.NET MVC:將 EditorFor() 與列舉的預設模板一起使用

  • April 16, 2011

我編寫了一個 EnumDropDownFor() 助手,我想將它與 EditorFor() 一起使用。我才剛剛開始使用 EditorFor(),所以對如何選擇模板有點困惑。

我的 Enum.cshtml 編輯器模板如下:

<div class="editor-label">
   @Html.LabelFor(m => m)
</div>
<div class="editor-field">     
   @Html.EnumDropDownListFor(m => m)
   @Html.ValidationMessageFor(m => m)
</div>

如果沒有明確定義要使用的模板,是否有任何方法可以在將列舉傳遞給 EditorFor() 時使用預設模板?

您可以查看 Brad Wilson 關於ASP.NET MVC 中使用的預設模板的部落格文章。當您擁有 Enum 類型的模型屬性時,它就是正在呈現的字元串模板。所以你可以像這樣自定義這個字元串編輯器模板:

~/Views/Shared/EditorTemplates/String.cshtml:

@model object
@if (Model is Enum)
{
   <div class="editor-label">
       @Html.LabelFor(m => m)
   </div>
   <div class="editor-field">     
       @Html.EnumDropDownListFor(m => m)
       @Html.ValidationMessageFor(m => m)
   </div>
}
else
{
   @Html.TextBox(
       "",
       ViewData.TemplateInfo.FormattedModelValue,
       new { @class = "text-box single-line" }
   )
}

然後在您看來:

@Html.EditorFor(x => x.SomeEnumProperty)

引用自:https://stackoverflow.com/questions/5683769