How do you keep the value of global variables between different Action Methods calls in MVC3?

后端 未结 5 1572
迷失自我
迷失自我 2021-01-04 01:48

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

I just discovered that I have some problems with global variables, probably because I am relati

5条回答
  •  醉梦人生
    2021-01-04 02:25

    First of all, there are no such thing as global variables in C#. What you're looking for is a static variable, which can be accessed through a class itself. Since a new controller instance is created on each request, the value of your variable is lost.

    You will need to declare your variable as such:

    private static string _MyGlobalVariable = "insert default value here";
    

    And access it as such:

    MyControllerClass._MyGlobalVariable
    

    Also, this variable will only be accessable from methods of the myController class, as you have it declared private.

    In addition to this, you will probably want to lock down the variable whenever using it, as you will end up running into race conditions eventually.

    note: I wouldn't suggest doing it this way

提交回复
热议问题