在Razor中使用静态变量 [英] Using Static Variables in Razor

查看:82
本文介绍了在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?

像这样

@using AppName.Models
<html>
<div ><h1 style="color:@GlobalVariables.SystemColor">System Color</h1></div>
</html>

推荐答案

据我所知,您可以从ASP.NET MVC的视图内部访问静态变量(如果包含)类的名称空间,并带有适当的using语句:

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

更重要的是,无论如何您都不应该直接从视图访问静态变量.与MVC模式保持一致,您的视图模型中的所有视图数据都应可访问:

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);
}

查看:

@model MyViewModel

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

如果需要在布局文件中执行此操作,则可以使用RenderAction调用控制器动作并返回部分视图.然后可以将partial输入为MyViewModel,可以像上面那样使用.

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.

这篇关于在Razor中使用静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆