MVC教程七:扩展HtmlHelper方法

在上一篇文章的最后,列出了一些常见的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标签为例进行扩展,扩展方法定义如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 7 namespace MvcHtmlHelper.Helper
 8 {
 9     /// <summary>
10     /// HTML的扩展类
11     /// </summary>
12     public static class HtmlHelperExt
13     {
14         /// <summary>
15         /// 用C#代码自定义一个span标签的扩展方法
16         /// </summary>
17         /// <param name="htlper"></param>
18         /// <param name="id"></param>
19         /// <param name="name"></param>
20         /// <param name="style"></param>
21         /// <param name="message"></param>
22         /// <returns></returns>
23         public static MvcHtmlString Messager(this HtmlHelper htlper, string id,string name, string style, object message)
24         {
25             if (message != null)
26             {
27                 TagBuilder builder = new TagBuilder("span");
28                 builder.MergeAttribute("style", style); //定义样式
29                 builder.MergeAttribute("id", id);     // 定义Id
30                 builder.MergeAttribute("name", name);  // 定义name
31                 builder.SetInnerText(message.ToString());
32                 //ToMvcHtmlString是在TagBuilderExtensions扩展类中定义的
33                 return builder.ToMvcHtmlString(TagRenderMode.Normal);
34             }
35             return MvcHtmlString.Empty;
36         }
37     }
38 }

 TagBuilderExtensions扩展方法定义如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcHtmlHelper.Helper
{
    public static class TagBuilderExtensions
    {
        public static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
        {
            System.Diagnostics.Debug.Assert(tagBuilder != null);
            return new MvcHtmlString(tagBuilder.ToString(renderMode));
        }
    }
}

 视图页面代码如下:

@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/dotnet261010/p/8900172.html