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
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; } else { 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
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.