Shared MVC Razor functions in several views

后端 未结 3 1574
眼角桃花
眼角桃花 2021-02-02 07:23

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

@functions 
{
    public HtmlString ModeImage(ModeEnum mode) 
    {
        switch(mode)
        {
          


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-02 08:09

    (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()
    {
        Something
    }
    
    @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()
    

提交回复
热议问题