I need to create a button in ASP.net that I can embed into another web page.
Essentially the button will query a DB server side on page load and then change it's image depending on the return of the query.
Does anyone know the best approach for this? I am not a pro at ASP.net as you can tell. Written in C# preferably.
In this case I would suggest using a
IHttpHandler
instead of a generic WebForm. https://msdn.microsoft.com/en-us/library/system.web.ihttphandler(v=vs.110).aspxThe handler is more suitable for this request as it will be able to respond quickly and is purpose built for handling specific requests that are not necessarily HTML based. This can be quite simple to wire up to accept a request, query the database and generate an image that you choose. Now you haven't provided much information about where the image comes from but lets look at a simple request.
To begin in a webforms web application select a new
GenericHandler
which we will nameDynamicImage.ashx
. Which will build our initial template as below.This template provides the basics to handle our request. When the request arrives the WebServer will execute the
ProcessRequest()
method passing in theHttpContext
as a parameter. From here we can use this to deliver our response.For argument sakes lets say we are querying the image based on the
QueryString
parameterusername
which represents a user in our database. I have included some basic code on your steps to achieve this. (Code commented)To call this handler you can simply set the
src
of the image to a path similar to/DynamicImage.ashx?username=johndoe
.Now your requirement may be slightly different. For example you may be retrieving the image from the database as a
byte[]
therefore instead of using thecontext.Response.TransmitFile()
method you may wish to use thecontext.Response.BinaryWrite()
method. This method transmits abyte[]
as the response stream.Finally I would refer you to another post (of mine) that talks about caching these images from a client perspective. This is very helpful if your button will be generated quite frequently. Leverage browser caching in IIS (google pagespeed issue)