C# 封装HtmlHelper组件:BootstrapHelper

2019-12-30 13:35:50王冬梅

编译发现报错如下

bootstraphelper,htmlhelper

将HtmlHelper转到定义发现它有两个构造函数,分别有两个、三个参数

bootstraphelper,htmlhelper

那么,我们的BootstrapHelper也定义两个构造函数,于是代码变成这样:


namespace Extensions
{
 public class BootstrapHelper : System.Web.Mvc.HtmlHelper
 {
  /// <summary>
  /// 使用指定的视图上下文和视图数据容器来初始化 BootstrapHelper 类的新实例。
  /// </summary>
  /// <param name="viewContext">视图上下文</param>
  /// <param name="viewDataContainer">视图数据容器</param>
  public BootstrapHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)
   : base(viewContext, viewDataContainer)
  { }
  /// <summary>
  /// 使用指定的视图上下文、视图数据容器和路由集合来初始化 BootstrapHelper 类的新实例。
  /// </summary>
  /// <param name="viewContext">视图上下文</param>
  /// <param name="viewDataContainer">视图数据容器</param>
  /// <param name="routeCollection">路由集合</param>
  public BootstrapHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)
   : base(viewContext, viewDataContainer, routeCollection)
  { }
 }
}

这样通过子类复用父类的构造函数的方式即可解决以上问题。编译通过!

2、定义LabelExtensions

上面我们研究过HtmlHelper,在HtmlHelper里面,不同的html组件定义了不同的Extension(扩展),下面我们就以最简单的Label标签为例定义我们BootstrapHelper里面的Label标签。

同样,在Extensions文件夹里面我们新建了一个文件LabelExtensions.cs,用于定义Label标签的扩展,它里面的基本实现如下:


namespace Extensions
{
 public static class LabelExtensions
 {
  /// <summary>
  /// 通过使用指定的 HTML 帮助器和窗体字段的名称,返回Label标签
  /// </summary>
  /// <param name="html">扩展方法实例</param>
  /// <param name="id">标签的id</param>
  /// <param name="content">标签的内容</param>
  /// <param name="cssClass">标签的class样式</param>
  /// <param name="htmlAttributes">标签的额外属性(如果属性里面含有“-”,请用“_”代替)</param>
  /// <returns>label标签的html字符串</returns>
  public static MvcHtmlString Label(this BootstrapHelper html, string id, string content, string cssClass, object htmlAttributes)
  {
   //定义标签的名称
   TagBuilder tag = new TagBuilder("label");
   //给标签增加额外的属性
   IDictionary<string, object> attributes = BootstrapHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
   if (!string.IsNullOrEmpty(id))
   {
    attributes.Add("id", id);
   }
   if (!string.IsNullOrEmpty(cssClass))
   {
    //给标签增加样式
    tag.AddCssClass(cssClass);
   }
   //给标签增加文本
   tag.SetInnerText(content);
   tag.AddCssClass("control-label");
   tag.MergeAttributes(attributes);
   return MvcHtmlString.Create(tag.ToString());
  }
 }
}