2011-04-20 62 views
1

因此,我正在關注this article來自定義Html.EditorForModel模板。它工作 - 很好。MVC3 Razor模板 - EditorForModel

我試圖將其轉換爲剃刀(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")被完全忽略,並且使用默認模板,因此知道爲什麼必須被稱爲「對象」將是一件很好的事情。

回答

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測試的方式。