Converting ASP.NET MVC Razor @helper function into a method of a helper class

后端 未结 2 1146
难免孤独
难免孤独 2020-11-27 22:15

Consider the following ASP.NET MVC razor view snippet which defines a helper

@helper FieldFor(Expression> expr         


        
2条回答
  •  情话喂你
    2020-11-27 22:40

    The signature would need to be

    public static MvcHtmlString FieldFor(this HtmlHelper helper, Expression> expression)
    

    Then you use a combination of TagBuilder and the inbuilt html helper methods to generate the html

    using System;
    using System.Linq.Expressions;
    using System.Text;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    namespace YourAssembly.Html
    {
      public static class FieldHelper
      {
        public static MvcHtmlString FieldFor(this HtmlHelper helper, Expression> expression)
        {
          MvcHtmlString label = LabelExtensions.LabelFor(helper, expression, new { @class = "control-label col-md-2" });
          MvcHtmlString editor = EditorExtensions.EditorFor(helper, expression, new { htmlAttributes = new {@class = "form-control"}})
           MvcHtmlString validation = ValidationExtensions.ValidationMessageFor(helper, expression, null, new { @class = "text-danger" });
    
           StringBuilder html = new StringBuilder();
           html.Append(editor);
           html.Append(validation);
           TagBuilder innerDiv = new TagBuilder("div");
           innerDiv.AddCssClass("col-md-10");
           innerDiv.InnerHtml = html.ToString();
           html = new StringBuilder();
           html.Append(label);
           html.Append(innerDiv.ToString());
           TagBuilder outerDiv = new TagBuilder("div");
           outerDiv.AddCssClass("form-group");
           outerDiv.InnerHtml = html.ToString();
           return MvcHtmlString.Create(outerDiv.ToString());
        }
      }
    }
    

    Then your can make it available in all you views by adding it to web.config

    
      
        
          
          ....
          
        
    

提交回复
热议问题