Writing @helper like inline helper method for ASPX view engine
This article was originally published for www.prowareness.com and could be located at http://www.prowareness.com/blog/writing-helper-like-inline-helper-method-for-aspx-view-engine/
When I started my MVC course with ASP.NET MVC 3, I got introduced to the @helper syntax with the Razor view engine. In case you didn’t know what an @helper syntax is, you may read more about it here. It is common that during training sessions, certain features of a technology may not appeal to you until you really use it, or until you have someone who puts that in perspective for you. So, I was dealing with an MVC application with ASPX view engine and I had a situation where I thought if I had Razor view engine, I could use the @helper syntax, and here’s what I ended up with.
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. – Source
In this post, I will show you can write a Razor style @helper method for ASPX view engine. Some people like to call it the Inline helper method If you look at the end result of the helper method in Razor view engine and ASPX view engine, it not aesthetically similar or lucid, but it solves the purpose – you get re-usability within the view. There are alternative ways of achieving the same thing using a Html helper of a server method within the view, but I ended with this approach.
In the ASPX view engine, if you declare and initialize a variable, if would show up in the intelli-sense. In the same way, if you try declaring an Action delegate, it would show up in the intelli-sense.
And that’s the trick. Declare an Action delegate, initialize with an anonymous delegate. You are done.
Note that when you initialize the Action delegate, you could either use the explicit delegate keyword or just a lambda.
Download: Sample projects including the source code for @helper sample in Razor view engine, and the Action delegate way of doing it in the ASPX view engine is downloadable at the SkyDrive location – http://sdrv.ms/15ykUXD