将ASP.NET MVC Razor @helper函数转换为辅助类的方法

blo*_*aak 4 c# asp.net-mvc razor

请考虑以下ASP.NET MVC razor视图片段,它定义了一个帮助器

@helper FieldFor<TModel>(Expression<Func<TModel, string>> expression)
{
    <div class="form-group">
        @Html.LabelFor(expression,
                       htmlAttributes:
                           new {@class = "control-label col-md-2"})

        <div class="col-md-10">
            @Html.EditorFor(expression,
                            new
                            {
                                htmlAttributes =
                                new {@class = "form-control"}
                            })
            @Html.ValidationMessageFor(expression, "",
                                       new {@class = "text-danger"})

        </div>
    </div>
}
Run Code Online (Sandbox Code Playgroud)

将它转换为类似于以下类的方法的模式是什么?

public static MvcHtmlString FieldFor(this HtmlHelper helper, FieldFor<TModel>(Expression<Func<TModel, string>> expression))
{
   /* Method */
}
Run Code Online (Sandbox Code Playgroud)

我发现的所有示例都专注于生成不依赖于其他HTML帮助程序的标记.

小智 5

签名需要

public static MvcHtmlString FieldFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
Run Code Online (Sandbox Code Playgroud)

然后使用TagBuilder和内置的html辅助方法的组合来生成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<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> 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());
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过将其添加到所有视图中使其可用 web.config

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      ....
      <add namespace="YourAssembly.Html" />
    </namespaces>
Run Code Online (Sandbox Code Playgroud)