好久沒在博客園發表文章了,今天來總結一下如何在asp.net mvc中添加自定義的HTML輔助方法。咱們如今設計這麼一個目前,利用自定義的HTML方法來渲染一個普通的img標記。直接進入主題吧:css
首先咱們先來看一下一個普通的img標籤在HTML中的代碼:html
<img src="Content/images/封面.jpg" alt="圖片" id="img01" width="500px" height="250px" class="img" style="" />
這個是咱們渲染以後從服務器端輸出到瀏覽器中的結果,那麼如今咱們來實現它。瀏覽器
第一步,咱們須要定義一個擴展方法,這個擴展方法就是用來渲染img元素的,代碼以下:bash
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; //注意:第一點,名稱空間必須爲System.Web.Mvc.Html namespace System.Web.Mvc.Html { //第二點,類名稱能夠爲任意名稱,可是必須爲靜態類 public static class CreateImageExtensions { /* public static MvcHtmlString Image(this HtmlHelper html, string id,string url,string width,string height,Dictionary<string,object> attributes) { TagBuilder tagHelper = new TagBuilder("image"); tagHelper.GenerateId(id); tagHelper.MergeAttribute("src", url); tagHelper.MergeAttribute("width", width); tagHelper.MergeAttribute("height", height); if (attributes!=null&&attributes.Count>0) tagHelper.MergeAttributes(attributes); return MvcHtmlString.Create( tagHelper.ToString()); }*/ //第三,擴展方法的名稱可使用任意名稱,可是此方法必須知足如下兩點: //01. 必須擴展自HtmlHelper類; //02. 方法的返回值類型必須爲:MvcHtmlString public static MvcHtmlString CreateImage(this HtmlHelper html, string id, string src, string width, string height,string cssClass, Dictionary<string, object> attributes) { TagBuilder tagHelper = new TagBuilder("img"); tagHelper.GenerateId(id); tagHelper.MergeAttribute("src", src); tagHelper.MergeAttribute("width", width); tagHelper.MergeAttribute("height", height); if (attributes != null && attributes.Count > 0) tagHelper.MergeAttributes(attributes); return MvcHtmlString.Create(tagHelper.ToString(TagRenderMode.SelfClosing)); } } }
這裏有三點值得注意的:服務器
1. 名稱空間必須爲System.Web.Mvc.Html,這一點相當重要;mvc
2. 類名稱能夠爲任意名稱,可是必須爲靜態類。事實上擴展方法也必須定義在一個靜態類中;框架
3. 擴展方法的名稱可使用任意名稱,可是必須擴展自HtmlHelper類,而且方法的返回值類型必須爲:MvcHtmlString。asp.net
固然方法的參數列表和實現代碼咱們能夠根據實際狀況來進行定義和書寫,我這裏只是簡單的整理一下步驟,個人實現代碼很簡單,僅僅是爲了解釋步驟。事實上類名和方法名也應該以具備「實際意義」的名稱來名稱,咱們能夠按照MVC框架的「約定」來進行命名,好比類名爲ImageExtensions,方法名爲Image等。值得注意的另外一點是,其實咱們能夠定義重載方法用來知足咱們的其餘需求,好比強類型的版本,這個能夠參考MVC框架的HTML輔助方法。ui
有了咱們剛剛說的三點,接下來就是在View中調用咱們剛剛定義的HTML輔助方法了,好比咱們在Index.cshtml文件中添加以下代碼:this
<div>@Html.CreateImage("img01", Url.Content("~/Content/images/IMG_9084_2寸藍底.jpg"),"551px","787px","imgCls", null)</div>
這個就和咱們通常的調用mvc框架的HTML輔助方法徹底一致。