How to create Html Helper in Asp.net MVC using Extension Method ?


HtmlHelper

Hi,

There are 2 option to create the Htmlheplers in Asp.net 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

Empty

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

HomeController

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;
            }
            else
            {
                return input.Substring(0, length) + ".....";
            }

        }

    }
}

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

Methodcall

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

Step 5: Run the application

Summary

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: