Thursday, September 18, 2008

ASP.Net - Custom Controls - embedded images not displaying

Problem: Briefly: You have written a custom control which uses an embedded resource image, which does not show up on the ASP page.

Indepth: You have created a custom ASP.Net control which uses images. You have included images in your project and you have set them to be embedded resources.

image 

And you load the images using "GetWebResourceURL". Like so - "Page.ClientScript.GetWebResourceUrl(this.GetType(), "ProjectName.FileName.ext");

You also verified that the method returns what looks like a valid url. (WebResource.axd? followed by a long string of characters). But you end up with the invalid image icon.

image

You check the dll in ILDASM and the resource is there.

image 

And yet - it does not show up on your web page.

You look through the project properties and you scratch your head and you scratch your head some more - and you still can't make it work.

Solution: Here is what you need to do to make it work: It is called the "WebResourceAttribute" and the documentation says that it "Defines the metadata attribute that enables an embedded resource in an assembly."

So add following line in the AssemblyInfo.cs file. (One for each image that should be served from your dll).

[assembly: WebResource("ProjectName.ImageName.gif", "image/gif")]

The second attribute is the "content-type". (Valid values for this can be found at - http://www.iangraham.org/books/html4ed/appb/mimetype.html)

That is it! You should now get to see the image in your control. image

No comments: