您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

签名必须是

public static MvcHtmlString FieldFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)

然后,您可以结合使用TagBuilder和内置的html helper方法生成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());
    }
  }
}

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

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      ....
      <add namespace="YourAssembly.Html" />
    </namespaces>
dotnet 2022/1/1 18:17:13 有457人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶