Wednesday, April 9, 2014

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.

clip_image002

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.

clip_image004

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.

clip_image006

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:

clip_image008

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.

clip_image010

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

0 comments :

Post a Comment