Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Static Variables in Razor

Tags:

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> 
like image 772
clifford.duke Avatar asked Jun 24 '13 09:06

clifford.duke


2 Answers

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:

@using WhateverNamespaceGlobalVariablesIsIn 

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:

public ActionResult MyAction() {     var model = new MyViewModel();     model.SystemColor = GlobalVariables.SystemColor;     ...     return View(model); } 

View:

@model MyViewModel  <div>     <h1 style="color:@(Model.SystemColor)">System Color</h1> </div> 

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 to MyViewModel, which can be used as above.

like image 145
Ant P Avatar answered Sep 22 '22 15:09

Ant P


your global class should be like

public class GlobalVariables {     public static string SystemColor     {         get { return Properties.Settings.Default.SystemColor; }     } } 

and in page @AppName.GlobalVariables.SystemColor appname replace by namespace of global class

@using AppName.Models <html> <div ><h1 style="color:@AppName.GlobalVariables.SystemColor">System Color</h1></div> </html> </p> 
like image 23
sangram parmar Avatar answered Sep 21 '22 15:09

sangram parmar