Using Static Variables in Razor

前端 未结 3 2017
清歌不尽
清歌不尽 2020-12-16 11:43

Why is it not possible to use a static Variable from a static class inside a view?

For example, lets say you have a Settings Class:

public static cla         


        
3条回答
  •  余生分开走
    2020-12-16 11:59

    You can access static variables in the view. There are three ways of doing this:

    1) As Ant P suggests, include using statement in the view. Given that the namespace of the GlobalVariables class is AppName.GlobalVariables:

    @using AppName.GlobalVariables
    
        

    System Color

    2) Another way is to directly use the namespace in the line where you want to access variable:

    System Color

    3) Finally, you can add needed namespace to the web.config file under Views folder:

    
      
      
        
          
          
          
          
          
          
        
      
    
    

    As for the sticking the variable in the Model and passing it to the View from there... indeed it conforms to the MVC pattern and assures separation of concerns and all that goodness. But in my opinion in some cases "sticking to the pattern" is taken to the level of absurd. In your case I'd just access this variable from the view.

提交回复
热议问题