8

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.

Community
  • 1
  • 1
Brian Mains
  • 50,520
  • 35
  • 148
  • 257

1 Answers1

12

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.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • Correct, this is the only way this can work in MVC right now. In the future will have a better story for global helpers. We just didn't have the time to get this to work. – marcind Feb 14 '11 at 03:48
  • Even with the web application template? – Brian Mains Feb 17 '11 at 04:00
  • @marcind What about ASP.NET MVC 4? Will there be others ways there to make global helpers? – Syska Mar 18 '12 at 20:40
  • Note that the standard @Html-Helper apparently doesn't work in App_Code, see http://stackoverflow.com/questions/4451287/razor-declarative-html-helpers. – theDmi Jul 17 '12 at 11:36