如何在asp.net mvc中添加自定义的HTML辅助种方法

很久没在博客园发表文章了,今天来总结一下如何在asp.net mvc中添加自定义的HTML辅助方法。我们现在设计这么一个目前,利用自定义的HTML方法来渲染一个普通的img标记。直接进入主题吧:

首先我们先来看一下一个普通的img标签在HTML中的代码:

<img src="Content/images/封面.jpg" alt="图片" id="img01" width="500px" height="250px" class="img" style="" />

  这个是我们渲染之后从服务器端输出到浏览器中的结果,那么现在我们来实现它。

第一步,我们需要定义一个扩展方法,这个扩展方法就是用来渲染img元素的,代码如下:

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,这一点至关重要;

2. 类名称可以为任意名称,但是必须为静态类。事实上扩展方法也必须定义在一个静态类中;

3. 扩展方法的名称可以使用任意名称,但是必须扩展自HtmlHelper类,并且方法的返回值类型必须为:MvcHtmlString。

当然方法的参数列表和实现代码我们可以根据实际情况来进行定义和书写,我这里只是简单的整理一下步骤,我的实现代码很简单,仅仅是为了解释步骤。事实上类名和方法名也应该以具有“实际意义”的名称来名称,我们可以按照MVC框架的“约定”来进行命名,比如类名为ImageExtensions,方法名为Image等。值得注意的另一点是,其实我们可以定义重载方法用来满足我们的其他需求,比如强类型的版本,这个可以参考MVC框架的HTML辅助方法。

有了我们刚刚说的三点,接下来就是在View中调用我们刚刚定义的HTML辅助方法了,比如我们在Index.cshtml文件中添加如下代码:

<div>@Html.CreateImage("img01", Url.Content("~/Content/images/IMG_9084_2寸蓝底.jpg"),"551px","787px","imgCls", null)</div>

  这个就和我们一般的调用mvc框架的HTML辅助方法完全一致。

猜你喜欢

转载自www.cnblogs.com/bob-bao/p/8975344.html