How EditorFor set ID and Name html attributes on form elements

三世轮回 提交于 2019-12-06 16:30:14

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") %>
Jon Galloway

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())

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!