C# 封装HtmlHelper组件:BootstrapHelper

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

三、BootstrapHelper组件完善

通过上面一系列发现坑、填坑的经历,一个最最简单的BootstrapHelper组件已经基本可用。我们将LabelExtensions简单完善下:


namespace Extensions
{
 public static class LabelExtensions
 {
  public static MvcHtmlString Label(this BootstrapHelper html, string id)
  {
   return Label(html, id, null, null, null);
  }
  public static MvcHtmlString Label(this BootstrapHelper html, string content)
  {
   return Label(html, null, content, null, null);
  }
  public static MvcHtmlString Label(this BootstrapHelper html, string id, string content)
  {
   return Label(html, id, content, null, null);
  }
  public static MvcHtmlString Label(this BootstrapHelper html, string id, string content, object htmlAttributes)
  {
   return Label(html, id, content, null, htmlAttributes);
  }
  /// <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());
  }
 }
}

呵呵,是不是有模有样~~可能又有人要说博主“山寨”了,呵呵,不管山寨不山寨,你觉得爽就行。

四、总结

这篇先到这里,一路填坑,基本功能总算可用。还有一些需要完善的地方,比如泛型,比如lamada表达式等等,来日方长,博主有时间完善下。还有最基础的一些表单控件,我们都需要封装,这个估计还有点工作量,只能慢慢来完善了,等完善都一定的程度会开源在git上,希望自己能够坚持下去!如果你觉得本文对你有帮助,请帮忙推荐下,您的推荐是博主坚持完善的动力。

以上所述是小编给大家介绍的C# 封装HtmlHelper组件之BootstrapHelper ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!