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.

1
  • 2
    depends on if it's user specific or application specific Commented Sep 11, 2012 at 8:34

4 Answers 4

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";

}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.