Render label for a field inside ASP.NET MVC 2 editor templates

I am 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 as follows:

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

But now I want to put everything <tr> inside the editor template, so I would like to have only this in my opinion:

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

And something like this in the editor, but I don’t know how to do for for the label attribute, for my example it should be Snippet_Created , the same as id \ name for the text field, so the pseudocode:

  <%@ 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() have the first parameter empty and id_ name for the text field is generated differently.

Thanks in advance!

+4
source share
3 answers

I found one solution here: Rendering a field name in EditorTemplate (displayed via EditorFor ())

But this seems a bit verbose, maybe it can be wrapped in a 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> 
+2
source

ViewData.ModelMetadata.PropertyName

0
source

Source: https://habr.com/ru/post/1307765/


All Articles