Save data through session in C# web application
Solution 1
You can store arbitrary values in Session
Session["someKey1"] = "My Special Value";
Session["someKey2"] = 34;
Or more complex values:
Session["myObjKey"] = new MyAwesomeObject();
And to get them back out:
var myStr = Session["someKey1"] as String;
var myInt = Session["someKey2"] as Int32?;
var myObj = Session["myObjKey"] as MyAwesomeObject;
Solution 2
ASP.NET webforms are stateless so this is by design.
you can store your bool variable in the ViewState of the page so you will always have it updated and persisted within the same page.
Session would also work but I would put this local page related variable in the ViewState as it will be used only in this page ( I guess )
Solution 3
Store the variable in a cookie! :)
Example:
var yourCookie = new HttpCookie("test", true);
Response.Cookies.Add(yourCookie);
Solution 4
Session["show_image"] = "true";
Ben2307
Updated on June 05, 2022Comments
-
Ben2307 about 2 years
I try to create a web application that got a button that change an image. this is my code:
public partial class _Default : System.Web.UI.Page { private bool test ; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (test) { Image1.ImageUrl = @"~/images/il_570xN.183385863.jpg"; test = false; }else { Image1.ImageUrl = @"~/images/BAG.png"; test = true; } } }
my problem is that the page reload every time. meaning, after i click the button "test" return to it's initial value. how can i have a variable that i can access all through the session?
please notice, i don't want to solve this specific image problem, but to know how to keep data until the user closed the page. -
Davide Piras almost 13 yearsbad idea to store in the session variables used only in 1 page!
-
Abbas almost 13 yearsI didn't say it is the perfect solution, he asked for A solution.. :)
-
Josh almost 13 yearsThe user specifically stated that the example above was not what he was trying to solve... rather how to store values until the user closed the browser. By definition that is
Session
-
Davide Piras almost 13 yearsyes you are right but from the code what he needs is clear and I told the difference in my answer :)