擴充HtmlHelper輔助方法

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   strong   

1、什麼是HtmlHelper輔助方法?其實就是HtmlHelper類的擴充方法,如下所示:

namespace System.Web.Mvc.Html{    public static class FormExtensions//表單相關擴充方法,例如建立表單標籤等。    public static class InputExtensions//這裡包含了所有input,例如:text,button,readiobutton等等。    public static class LinkExtensions//連結相關方法    public class MvcForm : IDisposable//與用戶端控制項無關    public static class RenderPartialExtensions//這是輸出PartialView    public static class SelectExtensions//輸出下拉框    public static class TextAreaExtensions//輸出多行文字框    public static class ValidationExtensions//輸出相關表單元素驗證。}

比如對於擴充類InputExtensions,MVC架構本身對此已有擴充:

namespace System.Web.Mvc.Html{    // Summary:    //     Represents support for HTML input controls in an application.    public static class InputExtensions    {                public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name);
}
}

2、通過對HtmlHelper進行擴充來構建自己的HtmlHelper輔助方法

System.Web.Mvc.Html下的HtmlHelper只能完成大部分html控制項的輸出,有一些我們經常用到的東東它卻沒有,怎麼辦?自己動手吧~

在我們擴充之前,有個叫TagBuilder的類(產生標籤)比較好用,你不必糾結於它的細節,只要大概知道他有那些方法就行:

    public TagBuilder(string tagName);    public void AddCssClass(string value);//增加樣式    public void GenerateId(string name);//設定控制項ID    private string GetAttributesString();    public void MergeAttribute(string key, string value);//設定屬性值    public void MergeAttribute(string key, string value, bool replaceExisting);    public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes);    public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting);    public void SetInnerText(string innerText);//設定顯示文本    public override string ToString();    public string ToString(TagRenderMode renderMode);//輸出控制項html

現在可以開始擴充了!

A、擴充img標籤

namespace System.Web.Mvc{    public static class ImageExtensions    {        public static string Image(this HtmlHelper helper, string id, string url, string alternateText)        {            return Image(helper, id, url, alternateText, null);        }        public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)        {            // 建立IMG標籤            var builder = new TagBuilder("img");            // 增加ID屬性            builder.GenerateId(id);            // 增加屬性            builder.MergeAttribute("src", url);            builder.MergeAttribute("alt", alternateText);            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));            // 輸出完整的img標籤            return builder.ToString(TagRenderMode.SelfClosing);        }    }}

調用:@Html.Image("img1", http://img/111.jpg, "這是一張圖片", new {border="4px"})

輸出:<img id="img1" src="http://img/111.jpg" style="border:4px;" alt="這是一張圖片"/>

B、擴充div標籤

namespace System.Web.Mvc{    public static class DivExtensions    {        public static String Div(this HtmlHelper helper, String id, String content, String cssStyle, object htmlAttrs)        {            TagBuilder builder = new TagBuilder("div");            //替換“.”為“_”            builder.IdAttributeDotReplacement = "_";            builder.GenerateId(id);                   builder.MergeAttributes(new RouteValueDictionary(htmlAttrs));            builder.AddCssClass(cssStyle);            builder.InnerHtml=content;            return builder.ToString(TagRenderMode.Normal);    //代表是雙面標籤        }    }}

調用:

@Html.Div("MyDiv.1", "擴充方法", "MyClassStyle", new { style="border:solid red 1px;" })

輸出:

<div id="MyDiv_1" class="MyClassStyle" style="border:solid red 1px;">擴充方法</div>

C、擴充Span標籤

namespace System.Web.Mvc{    public static class SpanExtensions    {        public static string Span(this HtmlHelper helper, string id, string text, string css, object htmlAttributes)        {            //創意某一個Tag的TagBuilder            var builder = new TagBuilder("span");            //建立Id,注意要先設定IdAttributeDotReplacement屬性後再執行GenerateId方法.            builder.IdAttributeDotReplacement = "-";            builder.GenerateId(id);                        //添加屬性                        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));            //添加樣式            builder.AddCssClass(css);            //或者用下面這句的形式也可以: builder.MergeAttribute("class", css);            //新增內容,以下兩種方式均可            //builder.InnerHtml = text;            builder.SetInnerText(text);            //輸出控制項            return builder.ToString(TagRenderMode.Normal);        }    }}

調用:

@Html.Span("span.test", "使用TagBuilder協助構建擴充方法", "ColorRed", new { style="font-size:15px;" })

輸出:

<span id="span-test" class="ColorRed" style="font-size: 15px;">使用TagBuilder協助構建擴充方法</span>

 

D、擴充ul、li標籤

namespace System.Web.Mvc{    public static class UlLiExtensions    {        public static MvcHtmlString UlLi(this HtmlHelper helper, string[] listItems)        {            TagBuilder ulTag = new TagBuilder("ul");            foreach (string item in listItems)            {                TagBuilder liTag = new TagBuilder("li");                liTag.SetInnerText(item);                ulTag.InnerHtml += liTag.ToString();            }            return new MvcHtmlString(ulTag.ToString());        }    }}

調用:

@Html.List(new string[]{"蘋果","柚子","草莓","火龍果"})

輸出:

<ul> <li>蘋果</li> <li>柚子</li> <li>草莓</li> <li>火龍果</li>  </ul>

E、擴充截取字串(某一個欄位太長,顯示的時候用來截取)

namespace System.Web.Mvc{    public static class CutStringExtensions    {        public static string CutString(this  System.Web.Mvc.HtmlHelper helper, string content, int length)        {            if (content.Length > length)            {                return content.Substring(0, length) + "...";            }            else            {                return content;            }        }    }}

此處只是拋磚引玉,更多的用法要根據實際需求來進行開發~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.