Reputation: 91
Have made several attempts to update an image in a master page div when switching between content pages. I first tried creating a master page property that I could update from the content page's Page Load event by declaring "MasterType VirtualPath=", but since the master is already loaded by this time it wasn't going to work. It did work when I set the ImageUrl in the master page's page load event (if !Page.IsPostBack then set the image's url attrib), so I know it can work, but I need the image to change for every content page I visit.
Then I tried using the master's menu button click events to set the ImageUrl before loading the content page but this also had no effect. I saw a thread suggesting the use of an UpdatePanel to hold the image, so I may try that next. What's the best way to do this..??
I wouldn't be surprised if a better way is to have the image in a content div instead, and updating that from the master. Any suggestions or links would be most welcome. I can post code if anyone would like to have a look. thanks.
Upvotes: 4
Views: 3911
Reputation: 26386
I don't know why you found it difficult. There are many ways to do this but I'll only show one. I just tested this and it worked. How?
In your master page, define your image and add runat="server"
<img src="put your default image.jpg" runat="server" id="changingImage" />
In your content pages, do this
protected void Page_Load(object sender, EventArgs e)
{
HtmlImage img = Master.FindControl("changingImage") as HtmlImage;
img.Src = "~/images/imageForContentPage1.jpg"; //replace this image based on your criteria
}
Possible exception is Null Reference
when the name of the image control specified in .FindControl
could not be found. Make sure it's exactly as you named it in the Master Page. And to prevent a Null Reference Exception, wrap a check around
if(img != null)
{
img.Src = "~/images/imageForContentPage1.jpg";
}
Upvotes: 4