Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access function defined in _ViewStart.cshtml

In an ASP.MVC application, I have a function defined in my _ViewStart.cshtml like this:

@functions
{
    public void Foo()
    {
      ....
    }
}

When I try to use this function in of my views, I get an exception saying that : The name 'Foo' does not exist in the current context I thought that all what I define in _ViewStart.cshtml is accessible to all my views that define it as layout.

I am missing something here ... Thank you for your help

like image 441
user385411 Avatar asked Aug 17 '26 09:08

user385411


1 Answers

You could place reusable functions them inside Razor views of the special App_Code folder.

For example inside ~/App_Code/Foo.cshtml you could declare a Bar function:

@functions {
    public static void Bar() {

    }
}

that will be accessible from any Razor view:

@{Foo.Bar();}

Also notice that the function must be declared as static.

like image 130
Darin Dimitrov Avatar answered Aug 19 '26 10:08

Darin Dimitrov