Home  > Resources  > Blog

Creating custom HTML helper functions in ASP.NET MVC

 
February 27, 2016 by Faheem Javed
Category: Microsoft

ASP.NET MVC provides several  HTML helper functions that generates HTML automatically. E.g. Html.TextBox, Html.CheckBox etc. We can also create our own custom helper functions as well. For creating HTML functions following steps have to be performed:

1. Create a static class

2. Add a static method that returns either string or MvcHtmlString

3. First Parameter should use this and it should be of  type HtmlHelper. HtmlHelper is the class to which we are essentially adding an extension method for each helper function.

Here are a bunch of helper functions:

public static class SimpleCustomHtmlHelpers
{
  public static MvcHtmlString SubmitButton(this HtmlHelper helper, 
                                                 string id, 
                                                 string title)
 {
   string str = string.Format("<input type='submit' id='{0}'” +
                                “ value='{1}' />",  id, title);
   return MvcHtmlString.Create(str.ToString());
 }
 public static string MailTo(this HtmlHelper helper, 
                                    string emailAddress, 
                                    string textToDisplay)
{
   return String.Format("<a href='mailto:{0}'>{1}</a>", 
         emailAddress, textToDisplay);
}
public static string Image(this HtmlHelper helper, 
                                   string imageUrl, 
                                   string altText)
{
   return String.Format("<img src='{0}' alt='{1}' />", imageUrl, altText);
}
}
Using the above code will let us use following helper functions:
1. Html.SubmitButton(‘btnSubmit’, ‘Register’) 
2. Html.MailTo(‘abc@xyz.com’, ‘Email’)
3. Html.Image(‘/images/img.jpg’,’image’)

Follow Us

Blog Categories