Thursday 2 January 2014

Create a HtmlHelper Methods - ASP.NET MVC

In this article we are going to see how to create a custom htmlhelper methods, which are used to generate the tags in MVC. what is Html Helper method for ex: in MVC we can see the Html.DisplayFor() is one of the Html Helper.

Now in our scenario we are going to create helper method for Button save and image. For button two overloads methods are created.

HTML HELPER:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EmpApp.HtmlHelpers
{
    public static class CustomHtmlHelper
    {

        public static IHtmlString SubmitButton(this HtmlHelper helper, string val,string classname)
        {
            TagBuilder tag = new TagBuilder("input");
            tag.Attributes.Add("type", "submit");
            tag.Attributes.Add("value", val);
            tag.Attributes.Add("id", val);
            tag.Attributes.Add("id", classname);
            return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
        }

        public static IHtmlString SubmitButton(this HtmlHelper helper, string val)
        {
            TagBuilder tag = new TagBuilder("input");
            tag.Attributes.Add("type","submit");
            tag.Attributes.Add("value",val);
            tag.Attributes.Add("id",val);
            return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
        }

        public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
        {
            TagBuilder tag = new TagBuilder("img");
            tag.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
            tag.Attributes.Add("alt", alt);
            return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
        }
    }
}


Razor View Code:

@model EmpApp.Models.Person

@{
    ViewBag.Title = "PersonInfo";
}

<div>
    @Html.EditorForModel()     
    @Html.SubmitButton("Save")
    @Html.Image("~/sam.jpeg","Sample")

</div>


Web.Config:
Add the namespace in the web.config EmpApp.HtmlHelpers

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="EmpApp.HtmlHelpers" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>



Output


From this article i hope you can learn how to create a custom html helper methods in MVC.

No comments:

Post a Comment