Custom Control with Embedded CSS and Images
Scenario:
I am creating an ASP.NET custom control (I will blog about it later) which requires embedded resources like CSS, JS and images. My control worked fine but the background image won’t show up.
My Initial Setup:
I set the Build Action for all my resources to “Embedded Resource”. Here is how I had my css and image entry in the AssemblyInfo.cs:
[assembly: System.Web.UI.WebResource("MyProjectName.styles.css", "text/css"][assembly: System.Web.UI.WebResource("MyProjectName.background.png", "image/png")]
And this is how I had my background image reference in my styles.css:
.myclass { width: 16px; height: 16px; background-image: url(background.png); }
Settings that fixed it:
After some investigation I found that the image is not found because it was being reference to my site location and not the embedded resource. After searching all over the net I found few hidden lines that solved the issues. Check the Resources below where I found that info.
Here are two changes I made to AssemblyInfo.cs and styles.css:
[assembly: System.Web.UI.WebResource("MyProjectName.styles.css", "text/css",PerformSubstitution=true)]
.myclass { width: 16px; height: 16px;background-image: url('<%=WebResource("MyProjectName.background.png")%>');}
What those changes do?
-
PerformSubstitution=true : The PerformSubstitution determines whether, during the processing of the embedded resource, other resource URLs are parsed and replaced with the full path to the resource. So when we set that to true the refernece to other web resources in the styles.css are resolved during the its parsing. In our case reference to background.png.
-
<%=WebResource("yourwebresource")%> : That is the syntax to get the link to actual webresource. So '<%=WebResource("MyProjectName.background.png")%>' will be replaced with actual url to the resource when the styles.css is parsed before serving it.
Resources / References :