7
votes

I'm running the razor code below in a .cshtml file (it's a simplified version of something more complex that I need to achieve), but the renderTestB helper does not seem to execute.

@renderTestA("test string 1", "test string 2");

@helper renderTestA(string input1, string input2)
{
    <div>
        @renderTestB(input1)
        @renderTestB(input2)
    </div>
}

@helper renderTestB(string input)
{
    <p class="test">@input</p>
}

Why is this? And is there another way of achieving what I'm trying to do?

I realise I could duplicate the paragraph code within the renderTestA helper, but would obviously prefer a re-usable code solution.

1
Is this good practice to introduce logic into your views? Why don't you write a custom helper?Matt
This is a practice left over from old versions of MVC. It is definitely better to use custom HTML helpers now.Brad C
This works fine for me.. when you say does not seem to execute do you mean you're not seeing the result you want? maybe there's something else wrong, since this is not your actual code it's hard to knowJamieD77
definitely not a nesting issue.. here is a dotnetfiddle with an example dotnetfiddle.net/7rojMIJamieD77
Thanks @JamieD77, you're absolutely right. It was an issue with my code. On my version I'd missed the @ sign that should have prefixed the function call inside a code block. Feel somewhat silly now. But at least you've taught me that helpers can indeed be nested, in addition to pointing me in the direction of my coding mistake!lozz

1 Answers

1
votes

What about something like this?

@renderTestA(renderTestB("test string 1"), renderTestB("test string 2"))

@helper renderTestA(string input1, string input2)
{
    <div>
        @input1
        @input2
    </div>
}

@helper renderTestB(string input)
{
    <p class="test">@input</p>
}

You should consider using Editor / Display templates or custom HTML helpers instead as the @helper functionality was used back before these features became the norm.

As to why you cannot nest them. It introduces a number of problems that are easily avoided by using the syntax I suggested above. Such as... if you have a circular loop of nested helpers, it could easily cause a stack overflow.