What are @Helpers in ASP.NET MVC Razor view engine pages?
Posted: (EET/GMT+2)
Working with the new Razor view engine in ASP.NET MVC application is a joy in my opinion, but sometimes, you find yourself writing the same blocks of Razor code again and again. To help with these kind of situations, the Razor view engine provides a feature called helpers, which can be added to any view page (.cshtml files) with the syntax "@helper".
For instance, say you were working with a view page to display product names and prices, but wanted to display something special if the price is above $1000, or the price is zero. It is simple to write the If statements for this, but if you needed to display multiple prices here and there around the page, copy-paste coding is soon your fate.
Instead, you could declare a Razor helper like this:
@helper ShowPrice(double price)
{
string result;
if (price > 999.99) { result = "Call us!"; }
else if (price > 0) { result = price.ToString("C"); }
else { result = "-"; }
@result
}
With this helper in place, you could have the following calls within your view page:
<h2>Product prices:</h2> <p>Product A: @ShowPrice(123.45)</p> <p>Product B: @ShowPrice(0.0)</p> <p>Product C: @ShowPrice(42.32)</p <p>Product D: @ShowPrice(4321.65)</p>
And with the Finnish locale set, the output would look like the following:
Product A: 123,45 € Product B: - Product C: 42,32 € Product D: Call us!
Very neat indeed!
This code works with ASP.NET MVC 3 and MVC 4 with the Razor view engine. For more information, check out ScottGu's blog post on the topic.