Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET MVC Custom HTML Helpers (C#)

0.00/5 (No votes)
6 Sep 2013 1  
Create custom HTML Helpers to make it easier to generate view content.

Create custom HTML Helpers to make it easier to generate view content. You can create custom helpers in three ways:

  1. with Static Methods
  2. with Extension Methods
  3. with @helper in the razor view

1. Static Methods:

CustomHelper.cs:
using System;
using System.Web.Mvc;

namespace HelperApplication.Helpers
{
     public static class CustomHelpers
     {
          public static string ImageTag(string src, string alt = "Image", int width = 50, int height = 50)
          {
               return String.Format("<img src='{0}' alt=’{1}’ width=’{2}’ height=’{3}’/>", src, alt, width, height);
          }
     }
}
  • src- image source (path)
  • alt- alternative text if image could not be loaded, and it is assigned a default value "Image". When no values is passed to this parameter it will take the default value "Image".
  • width and height- width and height of the image these parameters are also assigned a default value 50

Using the ImageTag HTML helper method..

Index.cshtml:
@using HelperApplication.Helpers.CustomHelper
<div>
     <span>ImageTag with default values for alt, width, height</span>
     @ImageTag("imagePath")
</div>
<div>
     <span>ImageTag with width=100 and height=100</span>
          @ImageTag("imagePath","Image With alt",100,100)
</div>

2. Extension Methods

3. @helper

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here