Tuesday, December 16, 2014

Reusable @helper methods in MVC

@helper methods in MVC Razor view

We all know that Razor view minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow.

Here we are going to know about a cool feature of Razor that a lot of people don’t know about – which is the ability to define reusable helper methods using the @helper syntax.

Here I have written the helper method for a simple logic of showing datetime string with different formats.


We’ve used the @helper syntax above to define a reusable helper method named “CustomizedDate”.  Just like a standard C#/VB method, it can contain any number of arguments (you can also define the arguments to be either nullable or optional).  Unlike standard C#/VB methods, though, @helper methods can contain both content and code, and support the full Razor syntax within them – which makes it really easy to define and encapsulate rendering/formatting helper methods.
You can invoke @helper methods just like you would a standard C# or VB method:
Reusing @helper methods across the project/application
In the above example, we have defined our @helper method within the same view page.  Alternatively, we can define the @helper method outside of our view page, and enable it to be reused across all of the views in our project.
We can do this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a\App_Code directory that you create at the root of a project.  For example, below I created a “MyHelpers.cshtml” file within the \App_Code folder, and defined my helper methods within the file. you can have any number of helper methods within each file.
Once our helpers are defined at the app level, we can use them within any view template of our application. Helpers1.png
Razor’s @helper syntax provides a convenient way to encapsulate rendering functionality into helper methods that you can reuse within individual view templates, or across all view templates within a project.
You can use this functionality to write code that is even cleaner and more maintainable.

Hope this helps,

Jude Vinnarasi Elizabeth

No comments:

Post a Comment