Extension Helpers Method in MVC

There are many ways to create your own helpers using Razor syntax. I am using one of them. The Helper Method is an optimum way to do it.
 
So let's start and create a Helper Method.

First we'll start with Extension Method syntax. I have created a sample application and it has HtmlHelpers.cs in the HtmlHelpers folder.

Image1.png
 
Open the HtmlHelpers.cs file and you will find the following code snippet, which is an Extension Method that takes two parameters and removes a string using the substring method.

image2.png
 
So far we have declared an Extension Method, now to use it in our View page (.cshtml). I'll use it in the Verify.cshtml page. Here is the code snippet of that page.

image3.png
 
As you can see we are using the RemoveString() Helper Method in the Verify.cshtml page, that caters the raw string (raw string as declared in the ViewBag.Message property) using two parameters being passed.
 
Now let's run this and see the execution:

image4.png
 
Notice that it took the complete string that we've passed, like @Html.RemoveString(ViewBag.Message as string, 20) and performs the code down the level.


Again Press F5 and see the result.

image5.png

 
Notice that it only gives you "Welcome to C#Corner" out of the complete string.
 
So this is how to create a Helper Method on demand in Razor view Engine. The sample application is attached as a reference.
 
Stay Happy Stay Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all