Render label for a field inside ASP.NET MVC 2 editor templates
I'm starting to use DataAnnotations in ASP.NET MVC and strongly typed template helpers.
Now I have this in my views (Snippet
is my custom type, Created
is DateTime):
<tr>
<td><%= Html.LabelFor(f => Model.Snippet.Created) %>:</td>
<td><%= Html.EditorFor(f => Model.Snippet.Created)%></td>
</tr>
The editor template for DateTime is like this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%=Html.TextBox("", Model.ToString("g"))%>
But now I want to put inside editor template the whole <tr>
, so I'd like to have just this in my view:
<%= Html.EditorFor(f => Model.Snippet.Created)%>
And something like this in editor template, but I don't know how to render for
for label attribute, it should be Snippet_Created
for my example, the same as id\name for textbox, so pseudo code:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<tr>
<td><label for="<What to place here???>">&开发者_StackOverflow社区lt;%=ViewData.ModelMetadata.DisplayName %></label></td>
<td><%=Html.TextBox("", Model.ToString("g"))%></td>
</tr>
The Html.TextBox()
have the first parameter empty and id\name for textbox is generated corectly.
Thanks in advance!
I found one solution here: Rendering the field name in an EditorTemplate (rendered through EditorFor())
But it seems a little verbose, may be it can be wrapped in custom 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>
ViewData.ModelMetadata.PropertyName
Similar approach using master pages: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-5-master-page-templates.html
精彩评论