如何在MVC3中的不同操作方法调用之间保留全局变量的值? [英] How do you keep the value of global variables between different Action Methods calls in MVC3?

查看:110
本文介绍了如何在MVC3中的不同操作方法调用之间保留全局变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Razor和C#开发ASP.NET MVC 3 Web应用程序.

I am developing an ASP.NET MVC 3 web application using Razor and C#.

我刚刚发现我在全局变量方面存在一些问题,可能是因为我对MVC比较陌生.

I just discovered that I have some problems with global variables, probably because I am relatively new to MVC.

我有一个带有一些全局变量和操作方法的控制器.我声明了一个全局变量,以允许操作方法对其进行操作并将操作反映到所有操作方法.我有以下情况:

I have a controller with some global variables and action methods. I declared a global variable in order to allow the action methods to manipulate it and reflect the manipulations to all the action methods. I have the following situation:

public class myController : Controller
{
    private string _MyGlobalVariable;

    public ActionResult Index()
    {
       _MyGlobalVariable = "Hello";
       //other code
       return View("MyView");
    }

    public ActionResult Print()
    {
       _MyGlobalVariable += "Print";

       return View("PrintView", _MyGlobalVariable);
    }
}

使用 Html.ActionLink() MyView 视图中调用 Print()操作方法.

The Print() action method is called with an Html.ActionLink() from the MyView View.

令人惊讶的是,未保留_MyGlobalVariable的值!因此,在指令_MyGlobalVariable += "Print"之前的 _MyGlobalVariable 的值等于null.

The surprising thing is that the value of _MyGlobalVariable is not kept! So the value of _MyGlobalVariable before the instruction _MyGlobalVariable += "Print" is equal to null.

我犯错了吗?如何在调用View之间保持全局变量的值?

Am I making some mistake? How can I keep the value of global variables between calls to Views?

谢谢

弗朗切斯科

PS:在我的特定情况下,全局变量是Dictionary<K,V>,但我想它不会改变逻辑.

PS: in my specific case the global variable is a Dictionary<K,V> but I guess it does not change the logic.

PPS:我知道您可以使用ViewModels而不是全局变量在操作方法之间传递数据,但就我而言,如果我使用的是Dictionary<K,V>,那么代码通常要少得多,通常我不将其包装在ViewModels中(我使用 POCO Lists<T>)

PPS: I know you can use ViewModels instead of global variables to pass data between action methods but in my case is much less code if I use a Dictionary<K,V> which usually I don't wrap in ViewModels (I use POCOs or Lists<T>)

推荐答案

每个请求都会获得一个新的控制器实例.
由于您的变量"是实例字段,因此不会持久存在.

Each request gets a fresh controller instance.
Since your "variable" is an instance field, it doesn't persist.

您可以通过将其设置为static或使用应用程序状态来解决该问题.

You can fix that by making it static, or by using application state.

但是,不要.
您绝对不应在Web应用程序中使用可变的全局状态.

However, don't.
You should never use mutable global state in a web application.

特别是,如果您同时收到两个请求,则您的字段会被弄乱.

In particular, if you get two request at the same time, your field will get messed up.

根据您要执行的操作,您可能需要使用会话状态或cookie.

Depending on what you're trying to do, you may want to use Session state or cookies.

这篇关于如何在MVC3中的不同操作方法调用之间保留全局变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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