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>
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With