2010-10-27 101 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> 
     } 
    } 
} 
相關問題