Using Functions and Helpers in ASP.NET Web Pages - WebMatrix
Posted by: Malcolm Sheridan
in Category ASP.NET
Abstract: The following article demonstrates how to use functions with helpers when you’re using ASP.NET Web Pages.
A few weeks ago I wrote an article on how to use helpers when you're using ASP.NET Web Pages. That article was written when WebMatrix was in Beta, but now it's released I want to share a little extra piece of functionality that I didn't in the previous article. Helpers are written in either Razor syntax, or even by creating class libraries in C# or VB.NET. In addition to helpers there are functions. Functions aid your helpers so you Don't Repeat Yourself (DRY) when creating helpers. Functions are defined by the functions keyword, and they're great if you want to maximize your knowledge.
Before you begin you need to install the latest version of WebMatrix. The current release can be installed easily through the Web Platform Installer. Once the install is finished you’re ready to begin.
Helpers reduce the code you need to write by implementing the Don’t Repeat Yourself (DRY) principal. For example I'm going to create a helper that either reduces or increase the cost of an item depending on what day of the week it is. Because this code can be used on multiple pages, I’m going to create a helper method. Helpers and functions go together hand in hand to reduce the code you might normally duplicate.
Helper methods can be created inside of WebMatrix, or alternatively they can be created in Visual Studio and referenced by your WebMatrix project.
Creating Helpers in Webmatrix
If you create Helpers inside of WebMatrix, you must first create a new folder called App_Code.
Any files inside of App_Code are compiled at runtime. The next step is to create the Helper. Start by adding a new cshtml or vbhtml file to the App_Code folder. For this example I’m going to create a Helper called PriceHelper. This file can be called anything you like. For common code inside helpers, you can create static methods and wrap these inside of functions. Functions are defined by the @functions keyword. Take a look at the code below.
I’ve created three functions, GetPriceDetails, GetDayAsNumber and GetDay. These functions reduce the duplicate code I would otherwise have in my helper method SetPrice. Functions must follow two rules:
The must reside in the @functions code block
The method must be static
If you make the function access modifiers public, then you could call these functions directly from your page. I would recommend not doing this as functions are supposed to be used by helpers, not directly from other areas of your code.
Know them, love them and use them!
The entire source code of this article can be downloaded over here