views:

413

answers:

3

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???>"><%=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!

+1  A: 

I found one solution here: http://stackoverflow.com/questions/1482925/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>
artvolk
A: 

ViewData.ModelMetadata.PropertyName

Eduardo Molteni
I have complex type (`Snippet.Created`) from my example. This property gives me only `Created`
artvolk