Matt R
Matt R

Reputation: 2617

How do you get the current image name from an ASP.Net website?

Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg.
Assuming I would use this code, where do you get the current images name.

string currImage = MainPic.ImageUrl.Replace(".jpg", "");  
currImage = currImage.Replace("~/Images/", "");

int num = (Convert.ToInt32(currImage) + 1) % 3;  
MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg";

The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg.
So in the process of loading the page, is it possible to pull the last image used from the pages properties?

Upvotes: 0

Views: 1666

Answers (7)

chakrit
chakrit

Reputation: 61538

@John ah Sorry I thought that your "refresh" meant postbacks.

In that case, just use a Session variable.

FYI, I suggested you use the ViewState dictionary instead of Session because the variable is used inside only that single page, so it shouldn't be using session-wide variable, that's bad practice.

Upvotes: 0

John Boker
John Boker

Reputation: 83719

@chakrit

does this really work if refreshing the page?

i thought the viewstate was stored on the page, and had to be sent to the server on a postback, with a refresh that is not happening.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 416059

It depends on how long you want it to persist (remember) the last viewed value. My preferred choice would be the SESSION.

Upvotes: 0

chakrit
chakrit

Reputation: 61538

You can store data in your page's ViewState dictionary

So in your Page_Load you could write something like...

var lastPicNum = (int)ViewState["lastPic"];
lastPicNum++;

MainPic.ImageUrl = string.Format("~/Images/{0}.jpg", lastPicNum);

ViewState["lastPic"] = lastPicNum;

you should get the idea.

And if you're programming ASP.NET and still does not understands how ViewState and web forms work, you should read this MSDN article

Understanding ViewState from the beginning will help with a lot of ASP.NET gotchas as well.

Upvotes: 5

John Boker
John Boker

Reputation: 83719

int num = 1;

if(Session["ImageNumber"] != null)
{
  num = Convert.ToInt32(Session["ImageNumber"]) + 1;
}

Session["ImageNumber"] = num;

Upvotes: 5

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391546

If you need to change images to the next in the sequence if you hit the F5 or similar refresh button, then you need to store the last image id or something in a server-side storage, or in a cookie. Use a Session variable or similar.

Upvotes: 0

bdukes
bdukes

Reputation: 156005

You'll have to hide the last value in a HiddenField or ViewState or somewhere like that...

Upvotes: 0

Related Questions