如何在 asp.net mvc 3 razor 视图中访问应用程序变量? [英] How do you access application variables in asp.net mvc 3 razor views?

查看:25
本文介绍了如何在 asp.net mvc 3 razor 视图中访问应用程序变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 global.asa.cs 中设置了一个 Application 变量:

 protected void Application_Start(){...//加载所有应用程序设置应用程序["LICENSE_NAME"] = "asdf";}

然后尝试像这样使用我的剃刀视图访问:

@Application["LICENSE_NAME"]

并得到这个错误:

编译器错误消息:CS0103:当前上下文中不存在名称应用程序"

正确的语法是什么?

解决方案

视图不应该从某处提取数据.他们应该使用从控制器操作以视图模型的形式传递给他们的数据.因此,如果您需要在视图中使用此类数据,正确的做法是定义一个视图模型:

公共类 MyViewModel{公共字符串 LicenseName { 获取;放;}}

让您的控制器操作从任何需要填充它的地方填充它(为了更好地分离关注点,您可以使用存储库):

public ActionResult Index(){var 模型 = 新的 MyViewModel{LicenseName = HttpContext.Application["LICENSE_NAME"] 作为字符串};返回视图(模型);}

最后让强类型视图向用户显示此信息:

@Model.LicenseName

这是正确的 MVC 模式,应该这样做.

避免像 pest 那样拉取数据的视图,因为今天是应用程序状态,明天是 foreach 循环,下周是 LINQ 查询,您很快就会在视图中编写 SQL 查询.

I set a Application variable in my global.asa.cs with:

    protected void Application_Start()
    {
        ...

        // load all application settings
        Application["LICENSE_NAME"] = "asdf";

    }

and then try to access with my razor view like this:

@Application["LICENSE_NAME"]

and get this error:

Compiler Error Message: CS0103: The name 'Application' does not exist in the current context

what is the proper syntax?

解决方案

Views are not supposed to pull data from somewhere. They are supposed to use data that was passed to them in form of a view model from the controller action. So if you need to use such data in a view the proper way to do it is to define a view model:

public class MyViewModel
{
    public string LicenseName { get; set; }
}

have your controller action populate it from wherever it needs to populate it (for better separation of concerns you might use a repository):

public ActionResult Index()
{
    var model = new MyViewModel
    {
        LicenseName = HttpContext.Application["LICENSE_NAME"] as string
    };
    return View(model);
}

and finally have your strongly typed view display this information to the user:

<div>@Model.LicenseName</div>

That's the correct MVC pattern and that's how it should be done.

Avoid views that pull data like pest, because today it's Application state, tomorrow it's a foreach loop, next week it's a LINQ query and in no time you end up writing SQL queries in your views.

这篇关于如何在 asp.net mvc 3 razor 视图中访问应用程序变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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