Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
478 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...