How to create Html Helper in MVC using Extension Method ?



There are 2 option to create the Htmlheplers in MVC i.e

1. using C# Extension Method
2. Using Razor declaration @Helper Sysntax

Here we will create very simple htmlhelper i.e Truncate. Whichone can be used for truncating the string.

Step1: Create the simple blank Mvc application, like this


Step 2: Add the Blank Controller i.e HomeController and Pass some long string Value from Controller to View i.e Index.


Step 3: Create C# HtmlHelpers class in Seperate Helper folder and Write the Extension Method to truncate the string like this

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

namespace RazorHelper.Helper
    public static class HtmlHelpers

        public static string Truncate(this HtmlHelper helper, string input, int length)
            if (input.Length <= length)
                return input;
                return input.Substring(0, length) + ".....";



Step 4: Build the application and Call the Helper Method in Index view like this


Note: Donot forget to call the namespace otherwise you canot call the extension Method.

Step 5: Run the application


Here we show how to implement Extension Method of C# in real application and How create the Html Helper on basis of our requirement.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.