@helper Syntax within Razor09/09/2013
This is pretty slick. Most folks think of razors as sharp objects used to cut things (e.g. 5 o'clock stubble). In my case I've got months of stubble. Us geeks often talk about another razor. ASP.NET MVC supports a view-engine option called “Razor” which minimizes the number of characters and keystrokes required when writing a view template. The view-engine enables a fast, fluid coding workflow.
Here's a great use case for DirigoEdge.
In Razor you can define inline functions in your View by utilizing the “@helper” keyword. It looks like this :
@helper PrintString ( string name )
<p> Hello @name</p>
@PrintString ( "World!" )
If you find yourself needing recursion or some sort of repeating action, then this might be the way to go. It can make your Views much cleaner as well by encapsulating rendering functionality.
Lastly, you can throw any helpers you’ve created inside a View in the “App_Code” folder of your project and they will be available throughout your project. They will show up in Intellisense and can be overloaded at run-time. Pretty powerful for a View Engine function.
I would recommend just creating an actual HTML helper extension if you find yourself needing reusable HTML output functions. In DirigoEdge there is a utility class already set-up to get you started called “HtmlHelperExtensions.cs”.
Here is some more great information on the helper syntax.
Did you know you can compile your Razor Views?
Maybe you want compile-time errors on your Views, or you just did some refactoring and want to make sure your view extensions got updated properly.
Just add this line to your .csproj file : <MvcBuildViews>true</MvcBuildViews>
Compiling your Views gives you a few benefits :
- You’ll avoid that initial runtime hit when your site first starts.
- You no longer need to deploy the .cshtml files to the server since they are compiled, resulting in a smaller deployment set.
- You can unit test your Views.