Declarative helpers in Razor

ASP.NET Web Pages Beta 1 have support for Helpers, which are methods written in C# or Visual Basic, and returns IHtmlString. They can return HTML that is displayed on the page. If you choose to create helpers that way, you would need to have your HTML in an assembly, which makes it different to modify. Because of that, the new version of Razor supports declarative Helpers that you can create directly on the page. They work in both ASP.NET MVC 3 Beta and ASP.NET Web Pages Beta 2, which is included in WebMatrix.

A declarative helper is created the same way as a method, but instead of having a return type, you set ”helper”.

Let´s say you have this code:

@{
    var text = "Hello, world!";
    <p>@text</p>
}

We want to refactor it into its own method to be able to reuse it. We can do it using a declative helper, like this:

@helper SayHello(string yadda)
{
    <p>Text: @yadda</p>
}

And if you want to use it:

@SayHello("Hello, world!")

We can also add code in the helper, such as:

@helper Calculator(int a, int b)
{
    @{
        var sum = a + b;
    }
    
    <b>@sum</b>
}

And to display the result, we use:

1 + 2 = @Calculator(1, 2)

It will display ”3” on the page, which is the sum of the numbers.

To go one step further and make it even more dynamic, we can use Lambda Expressions for the helper. If we want to be able to change how to count the result, we could use this instead:

@helper Calc(int a, int b, Func<int, int, int> calc)
{
    @{
        var sum = calc(a, b);
    }
    <p>@sum</p>
}

And if we want to multiply the letters, we use the helper this way:

@Calc(4, 4, (a, b) => a * b)

We can actually create really advanced helpers directly on the page. This is for those who are using ASP.NET Web Pages, but it can also be used in ASP.NET MVC 3 Beta.

6 Comments

Comments have been disabled for this content.