ASP.NET MVC HtmlHelper如何扩展
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Web.Mvc; namespaceTestMvcHelper { publicstaticclassHtmlExtensions { publicstaticMvcHtmlStringSubmit(thisHtmlHelperhelper,stringvalue) { varbuilder=newTagBuilder("input");//使我们创建的标签名字设为input builder.MergeAttribute("type","submit");//添加属性type="submit" builder.MergeAttribute("value",value); returnMvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)); } } }
(2)、Submit方法名是对应视图中调用的名称。(如:@Html.Submit("提交"))
(3)、thisHtmlHelper
(4)、varbuilder=newTagBuilder("input");
(5)、builder.MergeAttribute("type","submit")
(6)、builder.MergeAttribute("value",value);
(7)、TagRenderMode.SelfClosing
(8)、TagRenderMode是个枚举类,分别为
(9)、MvcHtmlString作为返回值是为了使返回值不被转义,比如"<"不会被转成"<"。
@Html.Submit("提交")
http://www.CodeHighlighter.com/-->1///<summary> ///带描述的链接扩展方法 ///</summary> ///<paramname="htmlHelper">要扩展的HtmlHelper类</param> ///<paramname="title">标题</param> ///<paramname="url">链接地址</param> ///<paramname="description">描述</param> ///<returns>HTML代码</returns> publicstaticMvcHtmlStringLinkWithDescription(thisHtmlHelperhtmlHelper,stringtitle,stringurl,stringdescription) { //生成与标题链接有关的HTML代码 TagBuildertitleContainer=newTagBuilder("p");//标题链接容器p TagBuildertitleLink=newTagBuilder("a");//标题中的文字要有链接,所以包含在a标签内 titleLink.MergeAttribute("href",url);//为a添加href属性并指定链接地址 titleLink.SetInnerText(title);//标题文字 titleContainer.InnerHtml=titleLink.ToString();//将a放到p中 titleContainer.AddCssClass("LinkTitle");//为标题添加样式 //生成与链接描述有关的HTML代码 TagBuilderdescriptionContainer=newTagBuilder("p");//连接描述容器p descriptionContainer.InnerHtml=description;//描述文字 descriptionContainer.AddCssClass("LinkDescription");//为描述添加样式 //将上述元素放入一个DIV中 TagBuilderdiv=newTagBuilder("div"); div.InnerHtml=string.Format("{0}{1}",titleContainer.ToString(),descriptionContainer.ToString()); //返回生成的HTML代码 returnMvcHtmlString.Create(div.ToString()); }