tags:

views:

1471

answers:

5

Hello,

I want to display a list of images and a description on a webpage using ASP.net MVC. The images are stored in a SQL Server DB and i'm getting them back as a byte[].

However, I don't understand how I can display a series of images on a page. I want to do something like this:

<% foreach(Product p in Model.Products)
      Response.Write(p.Description)
      Response.Write(html.Image(p.ImageArray)
%>

But the only code I've saw has been displaying a single image...

Thank you

Ben

A: 

Each image will have to be sent separately (which means creating an IMG request from the browser for each) or you will have to join them into a single image before sending back. If you run the code above it is likely you will see the first image only.

Otávio Décio
+1  A: 

You will need to create a custom IHttpHandler that will serve the images something like this:

    public class AlbumArt : IHttpHandler
        {
            public void ProcessRequest(HttpContext Context)
            {
byte [] b = your image...;
    Context.Response.ContentType = "image/jpeg";
                        Context.Response.BinaryWrite(b);
    }
    }

And then you would need to retrieve each image from there by using image tags in your html, something like

<img src="AlbumArt.ashx?imageId=1" />
Nick
A: 

Hi Nick,

I'll give that a go, sadly it means making two trips to the database as well - once to get the desc, and once for the image - any way around that?

Thanks

Ben

Ben Hall
Sadly there's not really a way around doing a request for each image. You could come up with some sort way to use css sprites, but that would be a lot of extra work and not much benefit unless your site has tons of traffic.
Nick
A: 

Images in HTML are external links, not embedded in the HTML itself. So you do need two requests. However you can optimize this a bit. In the first request, don't retrieve the image data itself, just the meta-data. Then in your HttpHandler, actually retrieve the binary image data.

DSO
+1  A: 

Rather than creating a new HttpHandler you can just write a controller action that returns the contents of the image file. Then add images to the page with their src attribute set to the action you created.

EDIT: Note that streaming images as byte[] from a database is inefficient compared to serving static files.

liammclennan