I have few layers of nesting custom user controls:
RegisterUser.aspx
开发者_JS百科 <%@ .... 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.
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) %>
Found the solution using the following two methods:
<%= Html.ViewData.TemplateInfo.GetFullHtmlFieldId("BirthDate") %>
<%= Html.ViewData.TemplateInfo.GetFullHtmlFieldName("BirthDate") %>
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())
精彩评论