Dissecting Razor, part 7: Helpers

We’ll continue our trek into Razor’s class-level features with helpers.

Helpers are one of Razor’s unique features.  They encapsulate blocks of HTML and server-side logic into reusable page-level methods. 

You can define a helper by writing @helper MethodName(parameters) { ... }.  Inside the code block, you can put any markup or server-side code.  The contents of a helper are parsed as a code block (like the contents of a loop or if block), so any non-HTML-like markup must be surrounded by <text> tags or prefixed by the @: escape.

Here is a simple example:

<!DOCTYPE html>
        @helper NumberRow(int num) {
            var square = num * num;
                <td>@(num % 2 == 0 ? "Even" : "Odd")</td>
                @for (int i = 0; i < 10; i++) {

Note that code statements (such as the square declaration) can go directly inside the helper body without being wrapped in code blocks – the direct contents of the helper is a code block, not markup.  Like any other code block, HTML-like markup is automatically treated as markup instead of code.

Like @functions blocks, helper methods can go anywhere in the source file; the physical location of the block is ignored.

Here is the generated source for the above example: (with blank lines and #line directives stripped for clarity)

public class _Page_Razor_Helpers_cshtml : System.Web.WebPages.WebPage {

    public System.Web.WebPages.HelperResult NumberRow(int num) {
        return new System.Web.WebPages.HelperResult(__razor_helper_writer => {

            var square = num * num;

            WriteLiteralTo(@__razor_helper_writer, "            <tr>\r\n                <td>");
            WriteTo(@__razor_helper_writer, num);

            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n                <td>");
            WriteTo(@__razor_helper_writer, square);

            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n                <td>");
            WriteTo(@__razor_helper_writer, num % 2 == 0 ? "Even" : "Odd");

            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n            </tr>\r\n");

    public _Page_Razor_Helpers_cshtml() {
    protected ASP.global_asax ApplicationInstance {
        get {
            return ((ASP.global_asax)(Context.ApplicationInstance));
    public override void Execute() {
        WriteLiteral("<!DOCTYPE html>\r\n<html>\r\n    <body>\r\n        ");
        WriteLiteral("\r\n        <table>\r\n            <thead>\r\n                <tr>\r\n                   " +
        " <th>Number</th>\r\n                    <th>Square</th>\r\n                    <th>E" +
        "veness</th>\r\n                </tr>\r\n            </thead>\r\n            <tbody>\r\n");

        for (int i = 0; i < 10; i++) {

        WriteLiteral("            </tbody>\r\n        </table>\r\n    </body>\r\n</html>\r\n");


Helpers are compiled as class-level methods that take a parameter set and return a System.Web.WebPages.HelperResult.  (This class name is configured by the RazorHostFactory)

Notice the the contents of the helper method are inside a lambda expression that takes a parameter named __razor_helper_writer.  This construction allows the helper to write directly to the HTTP response stream instead of assembling a giant string and then writing the string all at once.

The HelperResult constructor takes an Action<TextWriter> which contains the contents of the helper block.  The class implements IHtmlString and calls the action from the constructor to generate HTML.  However, under normal circumstances, this IHtmlString implementation is never called.

Calls to helper methods (@NumberRow(i)) are passed to the Write(HelperResult) overload.  This overload calls HelperResult.WriteTo(writer), which passes the page’s TextWriter directly to the helper’s lambda expression.  Thus, the lambda expression can write directly to the page’s output stream, without passing the output as a parameter to the helper method.

Looking inside the helper, we see that all content is passed to WriteTo and WriteLiteralTo methods, as opposed to the Write and WriteLiteral methods used by the rest of the page.

Helper methods cannot call the normal Write* methods since they aren’t necessarily writing to the current output (even though they usually do).  Therefore, they call these Write*To methods, which accept the TextWriter as a parameter.  These static methods are inherited from the WebPageExecutingBase class; their names are also configured by the RazorHostFactory.  The @ in the parameter is a little-used C# syntactictal feature that allows keywords to be used as identifiers; it has nothing to do with Razor’s use of the @ character.

Since helpers are compiled as normal methods, they can do almost anything that a normal method can.  However, because their contents are compiled inside a lambda expression, they have some limitations.  For example, helpers cannot use ref or out parameters, since they cannot be used inside lambda expressions.  Helpers can take params arrays or optional parameters.

Also, Razor’s C# code parser doesn’t support generic helper methods, although there is no reason that they couldn’t be supported in a later release.

The VB.Net code parser also doesn’t explicitly support generic helpers.  However, because VB.Net generics use parentheses, a VB.Net helper can declare a generic type parameter instead of a normal parameter list.

For example:

<!DOCTYPE html>

        @Helper PrintType(Of T)
        End Helper
        @PrintType(Of Dictionary(Of Integer, List(Of String)))()


This trick is not very useful.

Next Time: Static Helpers


Interesting to read about that


This article should read more people.
phone girls in London

Do you want to learn more about writing a proposal? On https://nerdymates.com/blog/how-to-write-a-proposal you can read more about it

We will discuss HTML which is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets and scripting languages such as JavaScript. It is also very useful for developers. Dissertation proposal writing services.

mr jatt Mp3 New Punjabi Song,Single Tracks Latest song download also Listen Latest Music Albums Online in High Quality at Mrpendus.in
mr jatt

I loved the article, keep updating interesting articles. I will be a regular reader I am offering assignment help to students over the globe at a low price.
doodle face online

It is important to seek english language essay writing services and english language coursework writing services since students find help when they visit English Language Writing Services.

I read this article and it appears to be very interesting seriously. It’s a kind of new post I’ve ever met. I want to know more interesting features for the future from you!!
Thanks for sharing this post!!
How to tell if your girlfriend has had bigger

Selection of good accounting tool is necessary as there is two tool quicken and quickbooks and both are accounting website but the difference is that and quicken is cheap small accounting tool and quickbooks is big all in one accounting tool with core accounting and payroll while comparing the quicken home and business vs quickbooks

Thanks for such wonderful blog that looks pretty different, I would suggest you please make a proper plan for your blog and start professional blogging as a career, One day you would be smart enough to earn some money, write my assignment for me wishing you a best of luck my friend, Thanks a lot for your nice support and love.

I will always let you and your words become part of my day because you never know how much you make my day happier and more complete. There are even times when I feel so down but I will feel better right after checking your blogs. help with dissertation You have made me feel so good about myself all the time and please know that I do appreciate everything that you have

Thanks for such wonderful blog that looks pretty different, I would suggest you please make a proper plan for your blog and start professional blogging as a career, One day you would be smart enough to assignment writing help earn some money, wishing you a best of luck my friend, Thanks a lot for your nice support and love.

Post a Comment