Tuesday 10 July 2012

ASP.NET MVC 3 and the @helper syntax within Razor

The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates. They enable better code reuse, and can also facilitate more readable code.

Key points:

  • 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 @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.

  • @helper method can be defined within the same view template as the code that called it. Alternatively, we can define the @helper method outside of our view template, and enable it to be re-used across all of the view templates in our project. We can accomplish 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.

@helper DisplayPrice(Decimal price)
{
      if(price == 0)
      {
         <span>FREE</span>
      }
      else
      {
         <text> <b>Price:<b> &pound;@(price) </text>
      }
}
Click here for more information about the @helper syntax

No comments:

Post a Comment