Tuesday, April 22, 2014

Extension Helpers Method in MVC

Extension Helpers Method in MVC

This article is more about the Custom Helpers and Extension Helper method in MVC with Razor View Engine.

There are lots of ways to create your own helpers using Razor syntax. I am using one of them. Helper method is an optimum way to achieve functionality.

So let’s start and create Helper method.

First we’ll start with Extension method syntax. I have created a sample application and it has HtmlHelpers.cs exist into HtmlHelpers folder.


Open HtmlHelpers.cs file and you will find the given below code snippet, which is an extension method which takes two parameters and does its operation to remove string using substring method.


So far we have declared extension method, now time is to use it into our View page (.cshtml).I’ll use it on Verify.cshtml page .Here is the code snippet of that page.


As you can see we are using RemoveString () Helper method on Verify.cshtml page, which cater the raw string (raw string as declared into ViewBag.Message property) with help of two parameters being passed.

Now let’s run this and see the execution:


Notice that it took the complete string which we’ve passed like @Html.RemoveString(ViewBag.Message as string, 20) and perform the code down the level.

Again Press f5 and see the result.


Notice that it only gives you "Welcome to C#Corner” out of complete string.

So this is how we can create Helper method on demand in Razor view Engine. Sample application is attached as a reference.

Stay Happy Stay Coding Smile


You can touch base with me here Sachin Kaila Profile


Post a Comment