Can you use a @Helper inside an @Helper?

强颜欢笑 提交于 2019-12-10 17:48:46

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/10522049/can-you-use-a-helper-inside-an-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!