Now that ASP.NET MVC 3 is in RC 2 and after reading some interesting blog posts on Razor’s syntax, I’ve decided to make some experiments building a simple Razor Helper. A helper is basically a snippet of code that you can create to generate some HTML using some code and that you can reuse in different part of your site.
What this Helper is about
Building and testing the Helper
To create and test my simple helper I’ve started creating a simple ASP.NET MVC 3 RC 2 project. Then I’ve added an App_Code folder that contains the Razor code. You can also build a library where to put your code, but to be more flexible I’ve followed the simple way. In the same folder I’ve put a file RazorHelpers.cshtml file. This name is important because I’ll use it to reference the helper in my code.
Now I declare some code inside the file: @helper keywork is used to create the helper, and the @funcions keywork to create some internal functions that I’ll call from helper itself. The file looks like the following, where FileGetContent is the function name of the Helper, it’ll be used as a static method.
I want to use the helper inside the _Layout.cshtml file in the Shared folder. This file is the template for the entire site, and now looks like:
The full code of helper is this one:
The logic of the helper is very simple, the FileGetContent call the function fun_fileGetContent that reads the content from file sytem, using different convention for the beginning of the file name or from the network, checking the common pattern using to express the name of the file, for example starting with http, or instead with ‘/’ char or ‘~’. Probably I need to add more code to make the helper more robust.
I’ve also tried to use the helper to add an inline image, so I’d like to have something like:
where I can literally embed a base64 encoded image inside an HTML img tag with the DataURI schema as in the previous image sample code. For that purpose I’ve created another helper, named FileGetBinaryContent: (I can’t use string encoding for array as in the previous code).
And now I can use the the code in my Razor View to insert an image of myself (of course, you can use others):
This is resulting page:
If you want to see the full example you can download the code from here.
In this post you have seen that you can create snippet of code that can be reused in different part of your site with a cleaner and compact syntax.