Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save data through session in C# web application

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.

like image 213
Ben2307 Avatar asked Mar 19 '26 10:03

Ben2307


2 Answers

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;
like image 173
Josh Avatar answered Mar 21 '26 23:03

Josh


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 )

like image 43
Davide Piras Avatar answered Mar 21 '26 22:03

Davide Piras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!