2011-04-16 89 views
18

我写了一个EnumDropDownFor()帮助器,我想和EditorFor()一起使用。我刚刚开始使用EditorFor(),因此对模板的选择有点困惑。ASP.NET MVC:使用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其中使用默认模板()?

回答

25

您可以结算Brad Wilson的博客文章,了解ASP.NET MVC中使用的default templates。当你有一个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) 
+0

好极了!已阅读该帖子,但没有意识到该字符串将被默认使用。这是使用的模板,如果它不能匹配其他任何东西? – ajbeaven 2011-04-16 09:38:36

+1

Can not get it work,as @if(Model is Enum)always always returns false as the Model is alwyes null !! ..我失踪了! ... 非常感谢。 – Hossam 2011-05-31 18:27:15

+1

应该使用@if(ViewData.ModelMetadata.ModelType.IsEnum)来代替检查实例,以便正确拾取nullabes。 – 2012-12-03 16:06:14