- On your element that contains the background-image, give it a name attribute (name="MyOjbject").
- On the same element, add another attribute: (runat="server").
- Now, in your code-behind file, on the Page_Load(…) event handler, add the following code:
MyObject.Style["background-image"] = "url(" + ResolveClientUrl(MyObject.Style["background-image"].Split(‘(‘).Split(‘)’)) + ")";
That’s it! Now you get the following advantages over other hacks:
The only place you maintain the image is in the same place you always have… in the background-image in the style.
The image remains visible at run-time in all content pages, regardless of where they’re located (how deep they are in other folders).
The image remains visible in VisualStudio at design time.
That big line of code is kind of complicated and really, for readability, could be broken down into the following:
string Image1 = MyObject.Style["background-image"].Split('(');
string Image2 = Image1;
string image3 = Image2.Split(')');
string imageurl = Image2;
string fixedimageurl = ResolveClientUrl(ImageUrl);
What’s really going on?
Well, the original problem is that if you have a background image hard coded into an element on your master page, content pages that derive from that master page, who are located in a different folder, will have the SAME image path, which is not valid from within the other folder. The code above figures out what path the content page is in and fixes the URL path of the background image attribute.
The image path is in the style element, within the "background-image" section as something like: "url(MyImages/MyPicture.jpg)". The code above parses that string by stripping off everything before the "(", including the "(". Then it strips off the ")" and anything after it. What’s left is the raw URL of the image. It then passes that to the method "ResolveClientUrl". This method figures out where you are and how to build a path that goes back to that URL. Then we wrap it in url(…).