扩展HtmlHelper方法

转自https://www.cnblogs.com/dotnet261010/p/8900172.html

在上一篇文章的最后,列出了一些常见的HtmlHelper的方法,这些都是ASP.NET MVC已经定义好的,如果我们想自己定义一个HtmlHelper方法可以吗?答案是肯定的,那么如何自定义一个HtmlHelper方法呢?

以Label()方法为例,查看Label方法的定义:

复制代码
 1 internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, IDictionary<string, object> htmlAttributes = null)
 2 {
 3             string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
 4             if (String.IsNullOrEmpty(resolvedLabelText))
 5             {
 6                 return MvcHtmlString.Empty;
 7             }
 8 
 9             TagBuilder tag = new TagBuilder("label");
10             tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
11             tag.SetInnerText(resolvedLabelText);
12             tag.MergeAttributes(htmlAttributes, replaceExisting: true);
13             return tag.ToMvcHtmlString(TagRenderMode.Normal);
14 }
复制代码

这是MVC的源码中对Label()扩展方法的定义,我们可以参考MVC中源码定义扩展方法的方式自定义一个扩展方法。

下面以span标签为例进行扩展,扩展方法定义如下:

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码

 TagBuilderExtensions扩展方法定义如下:

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码

 视图页面代码如下:

复制代码
@using MvcHtmlHelper.Helper;
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
    <p>
        <!--使用自定义的Messager方法-->
        @Html.Messager("lblMessage", "lblMessage", "color:red;font-weight:bold;", "自定义span标签")
    </p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>
复制代码

 运行结果如下:

 
 
原文地址:https://www.cnblogs.com/lidaying5/p/12757261.html