Shared MVC Razor functions in several views

2019-03-14 07:31发布

I have functions in my view that is shared by several pages:

@functions 
{
    public HtmlString ModeImage(ModeEnum mode) 
    {
        switch(mode)
        {
            case AMode: new HtmlString("<img etc..."); break;
            // more etc...
        }
    }
}

Is there a way to have it in a separate file and include it on each page without having to copy and paste it in to each one. I know I can write a .cs file and access it per page, but the function really concerns the view and I'de hate to have to recompile if this function changes.

3条回答
smile是对你的礼貌
2楼-- · 2019-03-14 08:10

(Here's a more detailed version of the existing answers.)

Create a folder called App_Code in the root of the MVC project if it doesn't already exist. In here, create an empty razor view and name it whatever you want:

MVC project with Razor view called Shared.cshtml inside App_Code folder

Add @helpers and/or static methods to it as needed:

@helper ShowSomething()
{
    <span>Something</span>
}

@functions
{
    public static int CalculateSomething()
    {
        return 1;
    }
}

Then use them from your views by first accessing the shared view by name:

@Shared.ShowSomething()
@Shared.CalculateSomething()
查看更多
Anthone
3楼-- · 2019-03-14 08:16

This sounds like you want the Razor @helper methods described in the blog post ASP.NET MVC3 and the @helper syntax within Razor by Scott Guthrie.

Here is the overview... "The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates. They enable better code reuse, and can also facilitate more readable code."

查看更多
家丑人穷心不美
4楼-- · 2019-03-14 08:17

You could make a static helper page and put a normal static method in the page.
You could then call it by writing PageName.MyMethod() anywhere, and I believe that you won't need to recompile the project.

查看更多
登录 后发表回答