【问题标题】:Render label for a field inside ASP.NET MVC 2 editor templates为 ASP.NET MVC 2 编辑器模板中的字段呈现标签
【发布时间】:2010-04-23 09:13:33
【问题描述】:

我开始在 ASP.NET MVC 和强类型模板助手中使用 DataAnnotations。

现在我的观点中有这个(Snippet 是我的自定义类型,Created 是 DateTime):

 <tr>
  <td><%= Html.LabelFor(f => Model.Snippet.Created) %>:</td>
  <td><%= Html.EditorFor(f => Model.Snippet.Created)%></td>
 </tr>

DateTime 的编辑器模板是这样的:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
 <%=Html.TextBox("", Model.ToString("g"))%>  

但现在我想将整个 &lt;tr&gt; 放入编辑器模板中,所以我想在我的视图中包含这个:

 <%= Html.EditorFor(f => Model.Snippet.Created)%>

在编辑器模板中有类似的东西,但我不知道如何为标签属性呈现for,对于我的示例,它应该是Snippet_Created,与文本框的id\name相同,所以伪代码:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
 <tr>
  <td><label for="<What to place here???>"><%=ViewData.ModelMetadata.DisplayName %></label></td>
  <td><%=Html.TextBox("", Model.ToString("g"))%></td>
 </tr>

Html.TextBox() 的第一个参数为空,并且正确生成文本框的 id\name。

提前致谢!

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 data-annotations


    【解决方案1】:

    我在这里找到了一种解决方案:Rendering the field name in an EditorTemplate (rendered through EditorFor())

    不过好像有点啰嗦,可能是可以用自定义的Html Helper包裹起来:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
    <tr>
        <td>
            <label for="
                <%= ViewData.TemplateInfo.HtmlFieldPrefix.Replace(
                        ".", 
                        HtmlHelper.IdAttributeDotReplacement) 
                %>">
                <%= ViewData.ModelMetadata.DisplayName %>:
            </label>
        </td>
        <td>
            <%= Html.TextBox("", Model.ToString("g")) %>
        </td>
    </tr>
    

    【讨论】:

      【解决方案2】:

      ViewData.ModelMetadata.PropertyName

      【讨论】:

      • 我的示例中有复杂类型 (Snippet.Created)。这个属性只给我Created
      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多