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 class GlobalVariables
{
public static string SystemColor
{
get { return Properties.Settings.Default.SystemColor; }
}
}
Why wouldn't you be able to call it in a view?
like so
@using AppName.Models
<html>
<div ><h1 style="color:@GlobalVariables.SystemColor">System Color</h1></div>
</html>
your global class should be like
and in page @AppName.GlobalVariables.SystemColor appname replace by namespace of global class
As far as I'm aware, you can access static variables from inside a view in ASP.NET MVC, if you include the class' namespace with the appropriate
using
statement:More importantly, you shouldn't be accessing static variables directly from views anyway. In keeping with the MVC pattern, all of your view's data should be accessible in your view model:
View:
If you need to do this in your layout file, you can use
RenderAction
to call a controller action and return a partial view instead. The partial can then be typed toMyViewModel
, which can be used as above.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 isAppName.GlobalVariables
:2) Another way is to directly use the namespace in the line where you want to access variable:
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.