3

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.

REMESQ
  • 1,190
  • 2
  • 26
  • 60

1 Answers1

2

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>
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • Thanks. I was trying to figure out `Func` and stupidly didn't realize I didn't need two parameters. +1 for the code sample. – REMESQ May 09 '12 at 22:45
  • Follow-up question: If I put `@helper Table(...)` in a file in `App_Code` and then try to, say call `Model.Entity` through an `if` statement I obviously get a "Cannot perform runtime binding on a null reference". I understand why I would get that error, but is there a way around that error? Or is it a limitation? Thank you again. – REMESQ May 10 '12 at 12:02
  • I think this a limitation of putting the helpers in `App_Code` what you can try is to pass the Model through another parameter to your `Table` like `@helper Table(dynamic model, Func otherHelper)` – nemesv May 10 '12 at 14:45