I’m working on an image gallery, where the user can upload images. The uploaded image is converted to a thumbnail and put in a specific folder for thumbnails, and the original image is put in a folder for full size images.
In Page_Load method in code behind i’m getting the thumbnails from the folder and bind them to the Repeater that i’m using, which means that all images in that folder are displayed when the page is loaded.
When a user chooses to upload an image the UploadButton_Click function is called, the file is processed and then displayed in full size. Everything works fine accept that the uploaded image thumbnail isn’t shown directly after it’s uploaded. To show it you must reload the page, so that Page_Load is loaded again.
Of course, an east way of solving this is to put the code for fetching the thumbnails and binding the Repeater control even in the UploadButton_Click function, but that is DRY which I don’t like.
Is there any better, more elegant way of solving this?
code behind:
protected void Page_Load(object sender, EventArgs e) {
var directory = new DirectoryInfo(Gallery.PhysicalApplicationPath + "/Images");
var theFiles = directory.GetFiles();
ImageRepeater.DataSource = theFiles;
ImageRepeater.DataBind();
var dataName = Request.QueryString["name"];
if (dataName != null) {
fullSizeImage.ImageUrl = "Images/" + dataName;
}
}
protected void UploadButton_Click1(object sender, EventArgs e) {
if (Page.IsValid) {
if (ImageUpload.HasFile) {
var content = ImageUpload.FileContent;
var name = ImageUpload.FileName;
var image = Gallery.SaveImage(content, name);
fullSizeImage.ImageUrl = "Images/" + image;
}
}
}
it’s to do with the page lifecycle. The Page_load is firing before the upload happens.
Try putting the code that populates thumbnails in the Page_PreRender Rather than the Page_Load.
That way it will get fired after the upload button click has taken place and not before.