栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368905.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号