好久没在博客园发表文章了,今天来总结一下如何在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辅助方法彻底一致。