1

I have few layers of nesting custom user controls:

RegisterUser.aspx

 <%@ .... Inherit="System.Web.Mvc.ViewPage<RegisterUserViewModel>"
 ...
 <%= Html.EditorFor(m => m.Details) %>
 ...

UserDetails.ascx

 <%@ .... Inherit="System.Web.Mvc.ViewUserControl<UserDetails>"
 ...
 <%= Html.EditorFor(m => m.BirthDate) %> <!--BirthDate is of type DateTime-->
 ...

and I have declared DateTime.ascx in Shared/EditorTemplates

 <%@ .... Inherit="System.Web.Mvc.ViewUserControl<dynamic>"
 ...
 <input type="text" id="???" />
 ...

The question is how to set input id attribute? I know that EditorFor makes some magic for default types. For example if DateTime was of type string, EditorFor will set id of input type to "Details_BirthDate" and the name attribute to "Details.BirthDate". I want to know how it's done? Because I want to use it for my special custom types.

tereško
  • 58,060
  • 25
  • 98
  • 150
devfreak
  • 1,201
  • 2
  • 17
  • 27

3 Answers3

1

How many levels of editor templates are you going to use? I really think the last one is redundant and you could use:

<%= Html.TextBoxFor(m => m.BirthDate) %>

By the way there's MVCContrib which is great. It has things like:

<%: Html.IdFor(x => x.BirthDate) %>

and:

<%: Html.NameFor(x => x.BirthDate) %>

which is really useful in some scenarios.


UPDATE:

Always use strongly typed editor templates:

<%@ .... Inherit="System.Web.Mvc.ViewUserControl<DateTime>"
<%: Html.TextBoxFor(x => x) %>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • the last layer - Html.TextBoxFor(m => m.BirthDate) - is not redundant because i want to make it fully custom, like datepicker and etc. So I really want to use custom control for the last layer – devfreak Nov 23 '10 at 22:04
  • See my update about using a strongly typed editor template for DateTime. – Darin Dimitrov Nov 23 '10 at 22:06
1

Found the solution using the following two methods:

<%= Html.ViewData.TemplateInfo.GetFullHtmlFieldId("BirthDate") %>

<%= Html.ViewData.TemplateInfo.GetFullHtmlFieldName("BirthDate") %>
devfreak
  • 1,201
  • 2
  • 17
  • 27
0

I think you're looking for ViewData.TemplateInfo.HtmlFieldPrefix. Example:

<input type="text" id="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>">

You can use GetFullHtmlFieldId if you need to specify a field, but if it's used in a Display or Editor Template you can just use HtmlFieldPrefix.

More info in this SO question: Rendering the field name in an EditorTemplate (rendered through EditorFor())

Community
  • 1
  • 1
Jon Galloway
  • 52,327
  • 25
  • 125
  • 193