且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

手把手教你写自定义HtmlHelper方法(Razor视图)

更新时间:2022-08-12 10:07:56

时间:2017-03-10
自定义HtmlHelper
在Models文件夹下新建一个类<code>“MyHtmlHelper”</code>
<b>想法一:</b>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace System.Web.Mvc.Html
{
     public static string MyTextBox(this HtmlHelper htmlHelper, string value)
        {
            return string.Format("<input type=\"text\" value={0}/>",value);
        }
}

在前端进行调用
<code>@Html.MyTextBox("老司机")</code>
但是出来的效果是这样的:


手把手教你写自定义HtmlHelper方法(Razor视图)
结果

完全不是我们想要的好吧(⊙o⊙)…
所以对于Razor视图,这种方法是行不通的
<b>想法二:</b>
所以我们查看一下IDE定义好的HtmlHelper方法是怎么写的


手把手教你写自定义HtmlHelper方法(Razor视图)
IDE中HtmlHelper的写法

所以我们把返回值做成MvcHtmlString类型,再来试试


手把手教你写自定义HtmlHelper方法(Razor视图)
代码补全提示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace System.Web.Mvc.Html
{
     public static MvcHtmlString MyTextBox(this HtmlHelper htmlHelper, string value)
        {
            //既然返回值类型都不是string类型了,所以我们return一个MvcHtmlString类型
            //在写MvcHtmlString的时候我们可以看到代码自动补全已经给出了一个提示,所以我们就用它试试效果
            //根据提示:使用指定文本值创建 HTML 编码的字符串,所以我们应该传入一个字符串,所以接下来的问题也就是我们需要把<input />做成一个字符串的形式
           return MvcHtmlString.Create();
        }
}

就像这样:

//用到了转义字符
string t=string.Format("<input type=\"text\" value=\"{0}\"/>", text);

所以我们自定义的HtmlHelper辅助方法应该长成这样:

        public static MvcHtmlString MyTextBox(this HtmlHelper htmlHelper, string text)
        {
            string t=string.Format("<input type=\"text\" value=\"{0}\"/>", text);
            return MvcHtmlString.Create(t);
        }

我们可以再进行几次重载

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace System.Web.Mvc.Html
{
    public static class MyHtmlHelper
    {
        /// <summary>
        /// 自定义的TextBox
        /// </summary>
        /// <param name="htmlHelper">扩展方法,不用传值</param>
        /// <param name="text">对应input的text</param>
        /// <returns></returns>
        public static MvcHtmlString MyTextBox(this HtmlHelper htmlHelper, string text)
        {
            string t=string.Format("<input type=\"text\" value=\"{0}\"/>", text);
            return MvcHtmlString.Create(t);
        }
        /// <summary>
        /// 自定义的TextBox
        /// </summary>
        /// <param name="htmlHelper">扩展方法,不用传值</param>
        /// <param name="value">对应input的value</param>
        /// <param name="text">对应input 的text</param>
        /// <returns></returns>
        public static MvcHtmlString MyTextBox(this HtmlHelper htmlHelper, string value,string text)
        {
            string t = string.Format("<input type=\"text\" value=\"{0}\" text=\"{1}\"/>",value,text);
            return MvcHtmlString.Create(t);
        }

    }
}

<b>谢谢O(∩_∩)O~</b>