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
  • 58,060
  • 25
  • 98
  • 150
Evgenyt
  • 10,201
  • 12
  • 40
  • 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
  • 30,112
  • 19
  • 130
  • 137
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
  • 22,767
  • 13
  • 83
  • 137