[英]ASP.NET MVC: Using EditorFor() with a default template for enums
I've written an EnumDropDownFor() helper which I want to use in conjunction with EditorFor(). 我编写了一个EnumDropDownFor()帮助器,我想与EditorFor()一起使用。 I've only just started using EditorFor() so am a little bit confused about how the template is chosen.
我刚刚开始使用EditorFor(),所以对模板的选择方式有点困惑。
My Enum.cshtml editor template is below: 我的Enum.cshtml编辑器模板如下:
<div class="editor-label">
@Html.LabelFor(m => m)
</div>
<div class="editor-field">
@Html.EnumDropDownListFor(m => m)
@Html.ValidationMessageFor(m => m)
</div>
Short of explicitly defining the template to use, is there any way to have a default template which is used whenever an Enum is passed in to an EditorFor()? 如果没有明确定义要使用的模板,是否有任何方法可以使用默认模板,只要将Enum传入EditorFor()?
You may checkout Brad Wilson's blog post about the default templates used in ASP.NET MVC. 您可以查看Brad Wilson的博客文章,了解ASP.NET MVC中使用的默认模板 。 When you have a model property of type Enum it is the string template that is being rendered.
当您拥有Enum类型的model属性时,它是正在呈现的字符串模板。 So you could customize this string editor template like this:
所以你可以自定义这个字符串编辑器模板:
~/Views/Shared/EditorTemplates/String.cshtml
: ~/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" }
)
}
and then in your view simply: 然后在你的视图中简单地说:
@Html.EditorFor(x => x.SomeEnumProperty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.