Introduction
This is a small tip on how to solve the Image refresh problem of Image control in ASP.NET.
Background
Many a times, I have observed that:
- (PREREQUISITE) I have an
Image
control on my page. - (STEP) I am uploading an image to be displayed on that control using
Fileupload
control. - (STEP) I upload an image and it gets displayed in Image control.
- (STEP) If I upload another image (no post-back in between and after a very short file)
- (PROBLEM) Many times, the new image file gets uploaded on the server, but the image control could not show the new Image.
Using the Code
The problem seems to occur when I am saving the uploaded image in some predefined file name. So first time the Image control recognized that the file is new, the next time since the file-name is the same, but actually the image is different, the Image control chooses not to refresh itself as it keeps thinking that the same file is getting attached to it again. (Perhaps this is some optimization mechanism inside.)
To avoid such problem in the scenario, I tried to cheat the image control every time I upload a new image file. I attach a dummy query string parameter with the image URL which makes the Image control reconsider and shows the new Image instead.
Since this is one scenario, I found this problem there could be other scenarios too so I made a habit of using the image control in the following manner:
imgphoto.ImageUrl = path + "?time="+ DateTime.Now.ToString();
This ensures that the Image control always displays the latest uploaded image and there will never be a scenario when the file saved on server is different from the image that is being displayed.
Points of Interest
I still am curious about why this happened in the first place. What I could make out of it is that it is some sort of optimization mechanism that is preventing unnecessary calls when then Image control's attached file path and newly supplied file path is same. Perhaps some gurus can confirm.
History
- 5th March, 2012: A simple solution based on dummy query string posted