2016年9月19日 星期一

[ASP.NET MVC] Html Helper Extensions


Just a note to myself...

Step 1: Custom Html Helper Extensions


namespace MvcExample.Extensions
{
    public static class WaspecExtentions
    {
        public static MvcHtmlString H2(this HtmlHelper htmlHelper, string content)
        {
            TagBuilder tagBuilder = new TagBuilder("h2");
            tagBuilder.InnerHtml = content;
            MvcHtmlString result = MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));  //<h2></h2>
            return result;
        }

        public static MvcHtmlString Hehehe(this HtmlHelper htmlHelper, string name, object value)
        {
            TagBuilder tagBuilder = new TagBuilder("input");
            tagBuilder.MergeAttribute("id", name);
            tagBuilder.MergeAttribute("name", name);
            tagBuilder.MergeAttribute("type", "text");
            tagBuilder.MergeAttribute("value", value.ToString());
            tagBuilder.MergeAttribute("class", "blueTextBox");
            MvcHtmlString result = MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));  //<input .../>
            return result;
        }
    }
}



Step 2: Use them


    @Html.H2("How are you!")
    @Html.Hehehe("textBox2""Hello!")




※ Other note for me:

    @Html.TextBox("textBox1"DateTime.Now, new { Blahblah="bbb", @class="blueTextBox"})<br/>
    <input type="text" id="textBox3" name="textBox3" value="@DateTime.Now" class="blueTextBox" />
    @Html.CheckBox("checkBox1",true) Are you ASP.NET MVC student?


沒有留言:

張貼留言