Keeping Background Images in MasterPages

DotNet, .NET, C#, MasterPages, background-image
 
Have you ever put a background image in an element on a MasterPage, only to find that the image won’t display if you have content pages in another folder?  Here’s a quick and dirty solution:
  1. On your element that contains the background-image, give it a name attribute (name="MyOjbject").
  2. On the same element, add another attribute:  (runat="server").
  3. 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(‘(‘)[1].Split(‘)’)[0]) + ")";

That’s it!  Now you get the following advantages over other hacks:

  1. The only place you maintain the image is in the same place you always have… in the background-image in the style.
  2. The image remains visible at run-time in all content pages, regardless of where they’re located (how deep they are in other folders).
  3. The image remains visible in VisualStudio at design time.

 You’re done!

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[1];
string image3 = Image2.Split(')');
string imageurl = Image2[0];
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(…).

That’s it.

Leave a Reply