Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declarative Helper Methods in Razor RTM

I saw Scott Guthrie's post about helper methods via his blog.

Specifically this:

I see the bunch of RC version of MVC 3 posts about the lack of helper methods... I see the syntactical support for it (@helper) gets highlighted, but I have this in /Views/Helpers/SomeHelper.cshtml (defined as a partial view):

@helper SomeHelper(string text)
{
    if (text != null)
    {
        <text>
            @text
        </text>
    }
    else
    {
        <text>
            Unknown
        </text> 
    }
}

I use it this way:

<div>
Helper with Text:
@SomeHelper("This is not null text.")
</div>

But I get SomeHelper is not defined.... so where did I mess this up? Is there something I need to do to register these views as helpers?

Thanks.

like image 970
Brian Mains Avatar asked Feb 14 '11 01:02

Brian Mains


1 Answers

I've done this by creating an App_Code folder in my project, then creating a Helpers.cshtml file in that folder.

Then, in an .cshtml view, use:

@Helpers.SomeHelper("This is not null text.")

This is the only way I've found to create shared declarative helper methods across the entire web project. If there are others, I'd like to hear about them.

like image 70
Drew Noakes Avatar answered Oct 20 '22 07:10

Drew Noakes