开发者

Save data through session in C# web application

I try to create a web application that got a button that change an开发者_如何学C 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.


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;


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 )


Store the variable in a cookie! :)

Example:

var yourCookie = new HttpCookie("test", true);
Response.Cookies.Add(yourCookie);


Session["show_image"] = "true";


To achieve what you want you need to check if is PostBack or not as so:

protected void Button1_Click(object sender, EventArgs e)
{

    if (test && !IsPostBack)
    {
        Image1.ImageUrl = @"~/images/il_570xN.183385863.jpg";
        test = false;
    }else
    {
        Image1.ImageUrl = @"~/images/BAG.png";
        test = true;
    }

}

BUT, don't do it that way. You are approaching this wrong. You wouldn't want to store in Session things like whether this image is shown or not, etc. It's difficult to suggest an approach without knowing the specific issue you are facing.


Another option than the already mentioned would be to store the data in the ViewState. If it's just used in postback situations, that might be a possible way.

ViewState["test"] = true;

You save memory on the server but use a little bit of bandwith. The data gets lost, when the user browses to another page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜