Reputation: 1606
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.
Upvotes: 0
Views: 14877
Reputation: 10012
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
Upvotes: 4
Reputation: 4732
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.
Upvotes: 3
Reputation:
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";
}
Upvotes: 5
Reputation: 1038710
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.
Upvotes: 4