Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

c# - Using Static Variables in Razor

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...