Last Updated: September 09, 2019
· spoike

Nesting Razor Helper Methods

The Razor view option called helper is something that's been available for developers since ASP.NET MVC3. Helpers work like any other methods exposed to Razor but it is composed of view code and the output is a HelperResult.

But did you know you can nest helpers in Razor? You can use the output from one helper and pass it in a containing helper that has a HelperResult as a parameter. Here is a quick example:

@helper Container(HelperResult stuff)
    <div class="stuff-container">
@helper Stuff(string s)
        Will the real @s, 
        please stand up?

Calling it in your Razor view is sort of what you expect when you compose them together like this:

@Container(Stuff("Slim Shady"))

The code above will output the following HTML where the code from the second helper is put inside the code in the containing helper:

<div class="stuff-container>
        Will the real Slim Shady, 
        please stand up?

The great thing with using HelperResult is that is quite dynamic, in such terms that you can use any other helper:

@* Another helper *@
@helper Sweet(string candy) {
    <p>I like @candy</p>

@* Invocation with the new helper *@

<!-- Outputs: -->
<div class="stuff-container>
    <p>I like lollipop</p>

But why?

Nesting the helpers will be useful for container of elements where you need to switch out the parts that are different inside that container. For example here is some helper code where the container can take the look of a "header" from another helper:

@helper ItemsContainer(string containerCssClass, HelperResult headerInfo, List<Item> items) {
    <article class="@containerCssClass">
        @foreach(var item in items) {
                    @Url.ActionLink(item.Title, ...)

The header can be anything, such as html-snippet with header tag and an icon (common icon font usage):

@helper Header(string text, string iconClass = null) {
        @if (!String.IsNullOrEmpty(iconClass) {
            <i class="@iconClass"></i>

The usage would be something like this, where the code needs to output several different kind of items:

            Header("News", "icon-news"), 

            Header("The Blog", "icon-blogpost"), 

Using helpers this way will cut down some of the errors of consistency in your HTML design that easily happens when you cut and paste similar snippets of code.

1 Response
Add your response

Can you make an example of how to do the same thing using extension methods?

over 1 year ago ·