简体   繁体   中英

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?

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.

int num = 1;

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

Session["ImageNumber"] = num;

您必须将最后一个值隐藏在HiddenField或ViewState或类似的地方...

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.

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

@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.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM