tags:

views:

93

answers:

5

I have a problem with static variable. Part of the organization of my controllers is as follows:

namespace MyApp.Controllers
{
    public class DevicesController : Controller
    {            
        static int some_var = 0;           

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SetValue(int temp){
           some_var = temp;
           return RedirectToAction("DisplayValue");
        }

        [Authorize]
        public ActionResult DisplayValue(){              
          .... 
          return View(some_object);
        }
     }
}

The problem arises when multiple users simultaneously using this view. The same static variable is used by all users and change its value. How solve this?

+6  A: 

Make it a private instance variable, not static.

If you need to maintain this count per user (but only for the given session), then you can do the following:

if (Session["Count"] == null)
    Session["Count"] = 0;
Session["Count"] = (int)Session["Count"] + MyNewValue;

If you want the count to persist across session, then you can persist it to a database.

RedFilter
If I make it private then I loss value of `some_var`.
Ognjen
It sounds like you want to maintain the value *per user*, so it should be persisted to Session, or to a database with the associated UserID.
RedFilter
Where I can found example for that
Ognjen
@Ognjen: see my update
RedFilter
Your code makes double lookup!
abatishchev
+1  A: 

Static variables (and properties) will be shared amongst all instances of that type -- in this case, your controller. The value will be lost when the application pool is restarted.

If you need the value to persist across requests, for a specific user, then you may need to look to move it to the session, or similar.

If you only need the value to remain for the duration of the current request, then a private variable would suffice.

Rowland Shaw
I need the value to persist across requests for specific user, any example for using static variables in sessions
Ognjen
Ognjen: The entire session object (HttpContext.Current.Session) is static. See Akash's response or look up how to use sessions in ASP.NET. :)
Helgi Hrafn Gunnarsson
+4  A: 

You can use,

HttpContext.Current.Session["some_var"]

instead of some_var, this will help. This will preserve for the user that is logged, one session, and you can access it statically with HttpContext.Current

namespace MyApp.Controllers 
{ 
    public class DevicesController : Controller 
    { 

        [AcceptVerbs(HttpVerbs.Post)] 
        public ActionResult SetValue(int temp){ 
           HttpContext.Current.Session["some_var"] = temp; 
           return RedirectToAction("DisplayValue"); 
        } 

        [Authorize] 
        public ActionResult DisplayValue(){ 

          ....  
          return View((int)HttpContext.Current.Session["some_var"]); 
        } 
     } 
} 
Akash Kava
Where I can found any example for work with save value to session state
Ognjen
I have this error when use your code:'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found (are you missing a using directive or an assembly reference?)
Ognjen
I'd suggest NOT using HttpContext.Current.Session. Just use Session, it's part of the ViewContext. Using HttpContext.Current is generally not a good idea in MVC land :)
CubanX
+1  A: 

There is an important difference between class variables and object variables. Static variables are class variables, this means all objects that are instantiated from a class share the same variable, so a change of that static variable in an object changes other objects of the same class too. But a nonstatic variable (object variable) is created for each instantiated object, so change doesnt effect others.

But the problem is not to choose between this two because your need is different. You need a variable that will be kept for each user. So as others stated, you must use a session variable.

But i think you should read about object variables and class variables.

huseyinalb
+1: An important distinction to understand for any programming task.
RedFilter
A: 

Your entire ASP.NET MVC application runs within an AppDomain, that is the application plus all requests being served for all users, everything!!

When you create a static variable, a single instance is declared and made available to the entire AppDomain, every request from every user will see the same value.

An instance variable (simply remove the 'static' word) is specific to an instance of the particular object it's in. In this case the object is an instance of your Controller, so your variable as an instance variable will be individual/specific to that controller object only. The ASP.NET runtime will create an instance of your Controller for each request it serves, then discard that controller object once its processed the request. So if you remove the static word, the variable will only stay around for the duration of that request, then disappear.

What you need, as other posters have said, is Session state. Session State lasts the duration of a session, as in someone browsing your site, and is specific to each user. So if you store that variable in Session State, it will be different for each user.

Problem is Session state disappears when the user leaves your website, so if you need it to the stay around longer, you then should use something like a database.


From your comments and original post, it sounds (and I'll try to put this as politely as possible) that you haven't quite grasped some Object-Oriented Programming idioms and concepts. While Session state isn't a OOP concept per se, the difference between static and instance variables is. I would recommend brushing up on these, as an understanding in these concepts (fundamental to OO programming) would mean, IMHO, you wouldn't even be asking this very question. I hope this answer has helped in your understanding somewhat.

Sunday Ironfoot