In the database I have a table that includes images contained in varbinary(max) column.
CREATE TABLE [dbo].[Album]( [AlbumId] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](max) NOT NULL, [Picture] [varbinary](max) NULL, ... ... CONSTRAINT [PK_Album] PRIMARY KEY CLUSTERED ( [AlbumId] ASC )
Next in my data access layer I've added a linq query to retrieve an image by albumId.
public byte[] GetAlbumCover(int albumId)
{
var q = from album in _db.Album
where album.AlbumId == albumId
select album.Picture;
byte[] cover = q.First();
return cover;
}
As for the actual MVC...
The controller:
public ActionResult RetrieveImage(int id)
{
byte[] cover = _BL.GetAlbumCover(id);
if (cover != null)
return File(cover, "image/jpg");
return null;
}
The view:
<% foreach (var item in Model) { %>
<tr>
<td>
<%: item.ArtistName %>
</td>
<td>
<%: item.AlbumName %>
</td>
<td>
<img src="/MusicInfo/RetrieveImage/<%:item.AlbumId%>" alt="" height=100 width=100/>
</td>
<td>
<%: Html.ActionLink("Edit", "Edit", new {id=item.AlbumId}) %>
</td>
</tr>
<% } %>
The link of the picture points to the controller (MusicInfo), the method inside the controller (RetrieveImage) & the specific image id to be able to retrieve it.
That's it...simple yet elegant.
Till next time
Diego