2014-09-22 57 views
1

给定一个看起来像这样的模板吗?在asp.net中级联编辑器模板的最佳方法mvc

<div class="form-group"> 
     <label class="control-label col-md-6">@Html.LabelFor(_ => _.A)</label> 
     <div class="col-md-6"> 
      @Html.EditorFor(_ => _.A) 
      @Html.ValidationMessageFor(_ => _.A, null, new { @class = "help-block" }) 
     </div> 
    </div> 
    <div class="form-group"> 
     <label class="control-label col-md-6">@Html.LabelFor(_ => _.B)</label> 
     <div class="col-md-6"> 
      @Html.EditorFor(_ => _.B) 
      @Html.ValidationMessageFor(_ => _.B, null, new { @class = "help-block" }) 
     </div> 
    </div> 
    (and repeat for every field) 

如何正确地对此进行参数设置。编辑器模板似乎不能级联。

换句话说,我认为需要的是将lambda作为模型参数的模板?

TemplateFor(x => x.Other)其中模板包含所有样板标记,并在正确的位置调用EditorForLabelForValidationMessageFor

EditorFor需要根据属性的类型选择正确的模板,就像通常那样。

+0

怎么样'@ Html.EditorForModel()'或'@ Html.EditorFor(x => x)'你有试过吗? – py3r3str 2014-09-22 15:46:05

回答

0

你可以把这一切都放在你的编辑器模板中。例如,您可以为String创建编辑模板:

查看\共享\ EditorTemplates \ String.cshtml

<div class="form-group"> 
    <label class="control-label col-md-6">@Html.Label("")</label> 
    <div class="col-md-6"> 
     @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue) 
     @Html.ValidationMessage("", null, new { @class = "help-block" }) 
    </div> 
</div> 

,然后,对于任何string财产,你只需要在你的下面观点:

@Html.EditorFor(m => m.SomeStringProperty) 

通知,有关编辑模板两件事情:

  1. 没有*For方法,而只是常规的HTML帮助程序。这可以让您避开需要进行初始表达的问题。
  2. 但是,常规方法要求您将属性名称指定为字符串,但谢天谢地,Razor会为您提供一个输出:如果您传递一个空字符串,它会为您输入正确的字符串。

冲洗并重复所有其他类型。有关更深入的概述,请参阅我的文章Display Templates and Editor Templates for Fun and Profit

相关问题