1

Is it possible to define a shared @helper in _ViewStart.cshtml so that it will be available for use in all views in its directory?

tereško
  • 57,247
  • 24
  • 95
  • 149
Evgenyt
  • 9,461
  • 12
  • 38
  • 44

2 Answers2

2

No, defining the @helper in _ViewStart will not work, but you can create a new Razor view for shared helpers and place it in the App_Code folder. One minor drawback is the helper must be called as a static method on a type with the same name as the view making this technique a little more verbose.

Here is an example:

Helper Method in View located here: ~/App_Code/RazorHelpers.cshtml:

@helper LiLink(string url, string title)
{
    <li><a href="@url">@title</a></li>
}

Helper Usage in a View:

@RazorHelpers.LiLink("/about","About")

See this SO Question: Razor Helper In App Code Folder

Community
  • 1
  • 1
James Lawruk
  • 28,217
  • 19
  • 123
  • 132
0

You can add the helper in a separate file and it will be available to all your views. See the Scoot Gu's post about it: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

Tomas Jansson
  • 21,761
  • 10
  • 75
  • 128