你如何访问asp.net MVC 3剃须刀意见应用程序变量? [英] How do you access application variables in asp.net mvc 3 razor views?

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

问题描述

我设置一个应用程序变量在我global.asa.cs有:

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

    protected void Application_Start()
    {
        ...

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

    }

,然后尝试访问像这样我的Razor视图:

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

@Application["LICENSE_NAME"]

和得到这个错误:

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>

这是正确的MVC模式,这就是它应该怎么做。

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

避免使用拉像害虫的数据视图,因为今天它的应用程序状态,明天这是一个的foreach 循环,下周它是一个LINQ查询,在任何时候,你最终的写作SQL查询你的看法。

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剃须刀意见应用程序变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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