MVC3 Razor模板 - EditorForModel

时间:2011-04-20 09:24:00

标签: templates asp.net-mvc-3 razor

所以,我正在关注this article来自定义Html.EditorForModel模板。如果它工作 - 很好。

我尝试将其转换为Razor(Object.cshtml)并获取:

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 
Compiler Error Message: CS0115: 'ASP._Page_Views_Shared_EditorTemplates_Object_cshtml.Execute()': no suitable method found to override

Source Error:


Line 44:         }
Line 45:         
Line 46:         public override void Execute() {
Line 47: 
Line 48: 

这是代码

@inherits System.Web.Mvc.ViewUserControl
@{  var count = 0; }
@if (ViewData.TemplateInfo.TemplateDepth > 1) { 
  @ViewData.ModelMetadata.SimpleDisplayText
} 
else { 
  <table class="form">
    <tr>
    @foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm))) {
      if(prop.HideSurroundingHtml) {
        @Html.Editor(prop.PropertyName) 
      } 
      else { 
        if(count == 2) {
          count = 0;
          @:</tr><tr>
        } 
        else {
          count++;
        }
        <td>hi
          <div class="editor-label" style="text-align: right;">
            @prop.IsRequired ? "*" : "" 
            @Html.Label(prop.PropertyName) 
          </div>
        </td>
        <td>
          <div class="editor-field">
            @Html.Editor(prop.PropertyName) 
            @Html.ValidationMessage(prop.PropertyName, "*") 
          </div>
        </td>
      } 
    } 
    </tr>
  </table>
} 

我没有猜测。

“有趣的是”当模板被称为“_Object.cshtml”时,@Html.EditorForModel("~/Views/Shared/EditorTemplates/_Object.cshtml")被完全忽略并使用默认模板,因此知道为什么必须被称为“对象”将是一个很好的知道。

1 个答案:

答案 0 :(得分:4)

尝试删除第一行(@inherits内容):

@{ var count = 0; }
@if (ViewData.TemplateInfo.TemplateDepth > 1) { 
  @ViewData.ModelMetadata.SimpleDisplayText
} 
else { 
  <table class="form">
    <tr>
    @foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm))) {
      if(prop.HideSurroundingHtml) {
        @Html.Editor(prop.PropertyName) 
      } 
      else { 
        if(count == 2) {
          count = 0;
          @:</tr><tr>
        } 
        else {
          count++;
        }
        <td>hi
          <div class="editor-label" style="text-align: right;">
            @if (prop.IsRequired)
            {
                @:*   
            }
            @Html.Label(prop.PropertyName) 
          </div>
        </td>
        <td>
          <div class="editor-field">
            @Html.Editor(prop.PropertyName) 
            @Html.ValidationMessage(prop.PropertyName, "*") 
          </div>
        </td>
      } 
    } 
    </tr>
  </table>
} 

还要注意我重写@prop.IsRequired测试的方式。