Forcing EditorFor to prefix input items on view with Class Name?

前端 未结 2 1143
心在旅途
心在旅途 2021-01-12 17:58

I have an EditorFor:

<%: Html.EditorFor(model => model.Client, \"ClientTemplate\", new { editing = false })%>

This will bind comin

2条回答
  •  执念已碎
    2021-01-12 18:14

    Try something like:

    <% Html.BeginHtmlFieldPrefixScope("Client") {
      Html.EditorFor(model => model.Client, "ClientTemplate", new { editing = false });
    <% } %>
    

    Every field you make with EditorFor, LabelFor and the likes will be prefixed.

    EDIT: Here's the extension method I'm using, sorry!

    public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
    {
      return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
    }
    

    ...and the class...

    private class HtmlFieldPrefixScope : IDisposable
    {
        private readonly TemplateInfo templateInfo;
        private readonly string previousHtmlFieldPrefix;
    
        public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
        {
            this.templateInfo = templateInfo;
    
            previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
            templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
        }
    
        public void Dispose()
        {
            templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
        }
    }
    

    See the link mentioned by Kohan in the comments below.

提交回复
热议问题