Rendering the field name in an EditorTemplate (rendered through EditorFor())

不打扰是莪最后的温柔 提交于 2019-11-28 18:19:33

You should be able to pull out the desired ID from the ViewData.TemplateInfo.HtmlFieldPrefix property of the view. Like this:

<%@ Control Language="C#"
      Inherits="System.Web.Mvc.ViewUserControl<System.XML.Linq.XElement>" %>
<textarea id="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>" class="html">
    <%= Model.ToString() %>
</textarea>

To show why this works, here's the place in TemplateHelpers.cs (of MVC2 Preview 1 source) where ViewData is initialized for the Editor template control:

ViewDataDictionary viewData = new ViewDataDictionary(html.ViewDataContainer.ViewData) {
    Model = modelValue,
    TemplateInfo = new TemplateInfo {
        FormattedModelValue = formattedModelValue,
        ModelType = modelType,
        HtmlFieldPrefix = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(expression),
        IsNullableValueType = (underlyingNullableType != null),
    }
};

In the call above, "expression" is initialized (further up the call stack) with the name of the property being edited.

BTW, @Sperling below caught a detail I originally missed: if you're using (or might use) a non-default HtmlHelper.IdAttributeDotReplacement, then you'll want to replace the dots in the HtmlPrefix property with HtmlHelper.IdAttributeDotReplacement.

Have been using this to generate id(with model prefix). Skip the .Replace() part if you want the name attribute.

<%=Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty).Replace(".", HtmlHelper.IdAttributeDotReplacement) %>

In our case we had to use Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName with ExpressionHelper.GetExpressionText

which in razor was used like this:

           // hiddenFor was caching the value of this html input, and the value alone, nothing else on the page!
            Expression<Func<Web.ViewModels.ApiSettingsViewModel, int>> expression = (m => m.OrgApiLoginCredentials[i].OrgApiLoginId); 
        }
        <input type="hidden" value="@Model.OrgApiLoginCredentials[i].OrgApiLoginId" name="@Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))" class="data-org-api-login-id"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!