2010-10-27 59 views
12

我正在为Object.cshtml创建一个编辑器模板来更改Html.EditorForModel()方法的行为。我找不到任何使用Razor的例子。我已经看到使用MVC2和WebForm视图引擎的this example,但对剃须刀没有足够的了解来转换它。即使是一个简单的例子也会非常有帮助。使用MVC和Razor创建object.cshtml编辑器模板

回答

21

我只是做显示模板,剩下的作为一个练习留给读者:)

@if (Model == null) { 
    <text>@ViewData.ModelMetadata.NullDisplayText</text> 
} else if (ViewData.TemplateInfo.TemplateDepth > 1) { 
    <text>@ViewData.ModelMetadata.SimpleDisplayText</text> 
} else { 
    <table cellpadding="0" cellspacing="0" border="0"> 
    @foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) { 
     if (prop.HideSurroundingHtml) { 
      <text>@Html.Display(prop.PropertyName)</text> 
     } else { 
      <tr> 
       <td> 
        <div class="display-label" style="text-align: right;"> 
         @prop.GetDisplayName() 
        </div> 
       </td> 
       <td> 
        <div class="display-field"> 
         @Html.Display(prop.PropertyName) 
        </div> 
       </td> 
      </tr> 
     } 
    } 
    </table> 
} 
+0

感谢这个,但是当我将此代码粘贴到我的object.cshtml我得到“错误CS1024:预处理器可怕ctive期待“ – Craig 2010-10-27 02:51:33

+2

Doh,你的代码是正确的。我不小心拥有了#Html.EditorForModel()而不是@ Html.EditorForModel()。至少你的代码不会被浪费,并且将来会被许多新的Razor用户首先看到。 – Craig 2010-10-27 02:53:58

+0

我甚至无法让我的Object.cshtml执行。我把它放在Views/Shared/EditorTemplates/Object.cshtml任何想法? – 2011-06-29 20:19:57

0

这似乎为编辑模板工作的引导,请让我知道的任何改进

Object.cshtml

@if (Model == null) 
{ 
    <text>@ViewData.ModelMetadata.NullDisplayText</text> 
} 
else if (ViewData.TemplateInfo.TemplateDepth > 1) 
{ 
    <text>@ViewData.ModelMetadata.SimpleDisplayText</text> 
} 
else 
{ 
    foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) 
    { 
     if (prop.HideSurroundingHtml) 
     { 
      <text>@Html.Editor(prop.PropertyName)</text> 
     } 
     else 
     { 
      <div class="form-group"> 
       @Html.Label(prop.PropertyName, new { @class = "control-label col-md-2", @style = "text-align:right;" }) 
       <div class="col-md-10"> 
        @Html.Editor(prop.PropertyName, null, new { @class = "form-control " }) 
        @Html.ValidationMessage(prop.PropertyName, "", new { @class = "text-danger" }) 
       </div> 
      </div> 
     } 
    } 
}