0

I need to save a value for all my website, is there a way to save it in a global variable in the server side like ViewData for example or is it better to save it in a cookie ?

This data is set using a dropdown list and cached in the controller.

Thanks.

Ryan McDonough
  • 9,732
  • 3
  • 55
  • 76
MaT
  • 1,556
  • 3
  • 28
  • 64

4 Answers4

5

In the Global.asax page

void Application_Start(object sender, EventArgs e)
{
    // set your variable here
    Application["myVar"] = "some value";
}

Inside the action

public ActionResult MyAction()
{
    // get value
    string value = Application["myValue"].ToString();

    // change value
    Application["myValue"] = "some NEW value";

}
4

You could store it in the Application state:

public ActionResult Foo()
{
    HttpContext.Application["someKey"] = "some value";
    ...
}

and then later read from it:

string value = (string)HttpContext.Application["someKey"];

The values stored in the Application state are shared among all users of the website.

If you need to store user specific data you could use session or cookies depending on whether it is sensitive data or not.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
4

Session would be the way if you are wanting to change the value, if the value is going to be static & is known before the application loads any data then you could store it in the Web.config and reference it from there.

Such as:

<appSettings>
   <add key="MyStaticItem" value="Lulz" />
</appSettings>

So then if you want to retreive that string you can do:

Meh = ConfigurationManager.AppSettings["MyStaticItem"] 

Meh would be Lulz

Gareth
  • 5,140
  • 5
  • 42
  • 73
Ryan McDonough
  • 9,732
  • 3
  • 55
  • 76
3

Can also use session like this:

Session["MyKey"] = "MyValue";

and retrieving like this:

var myVar = (string)Session["MyKey"];

if that's per user value.

Hope this is of help.

Display Name
  • 4,672
  • 1
  • 33
  • 43