Search code examples
asp.net-mvc-3razorrazor-declarative-helpers

Can you use a @Helper inside an @Helper?


I am not sure this is possible.

I have a bunch of @Helper's inside a view AND in other views:

@helper ViewHelper1()
{
   ...
}
@helper ViewHelper2()
{
   ...
}
etc.

I have repetitive code that is used in the view AND in other views:

@if (!(Model.Entity == Model.Enum.One))
    {
        <td>
            @ViewHelper1()
        </td>
    }
    else
    { 
        <td>
            @ViewHelper1()
        </td>
        <td>
            @ViewHelper1()
        </td>
    }

The actual @ViewHelper1 has more complex code, but that's not important (I think).

Well, since each view has a number of @Helper's (30+ views, 10-15 @Helper's each) and the <table> structure is the same, I was wondering how to go about creating a @Helper in App_Code that encapsulates the <td> structure and then would pass the view's @Helper.

Say:

@helper Table(...) 
    {
        ...
    }

Or whether or not that's even possible and then call it in the view like:

@Table(HelperView1)

If it is I just needed help with the syntax.

As always, much appreciated.


Solution

  • The generated razor helpers are just functions with the return type HelperResult. You can have delegates which returns HelperResult as parameters in your main helper and call them at the appropriate places.

    A small sample to get you started:

    @helper View1()
    {
        <h1>View1</h1>
    }
    
    @helper View2()
    {
        <h2>View2</h2>
    }
    
    @helper Table(Func<HelperResult> viewHelper)
    {
        <text>Reuslt of viewHelper</text>
        @viewHelper()
    }
    
    @Table(View1)
    @Table(View2)
    

    The generated output:

    Reuslt of viewHelper
    <h1>View1</h1>
    
    Reuslt of viewHelper
    <h2>View2</h2>