Reusable Methods in Razor View Using Inline Helper(s)

Introduction

With the release of MVC 3, Microsoft has developed the Razor View Engine that is developer-friendly and cleaner then web forms.

This article describes a beautiful feature called inline helper of Razor.

Using inline helpers we can re-use methods defined in a View (and not in a controller).

Note: It's not a good practice to define business logic in View.

Creating a Simple MVC 4 Application

Choose a new project type MVC4.

new project

Then choose the template basic and view type Razor. It will create default structure for the MVC application.
 
default structure for MVC

Then we need to add a new controller named HomeController.

Add a simple view
 
Add a simple view

Adding Inline Helper method to View

For keeping things simple I will create a simple greeting method that will return “Good Morning”, “Good Afternoon” and “Good Evening” depending on the current time.

Here is the Index view.
 
Adding Inline Helper method

I have created the Greeting() helper method and as we can see we can call this helper method just by using"
  1. @Greeting()  
But what problem is that?

We can use this method for the current View.

What if we want the same method for more then one view?

We use Global Helpers for that. I am a little confused about whether I should use a Helper Method or only a Helper.

Defining Global Helper Method

We need to define global helpers inside the App_Code folder (actually the razor view is compiled at run time so if we put our view into App_Code then it will be precompiled).

Please see the snapshot below.
 
Global Helper Method

Now if we define the same helper method in the InlineHelpers.cshtml file within the App_Code folder then we can access it simply using:
  1. @InlineHelpers.Greeting()  

Summary

In this article we had gone through Helper Methods and saw how to use Inline helpers for a single view or for globally.

I will be looking forward to reader's questions and comments.


Similar Articles