Loading images from database in mvcmusicstore sample

mvc musicstore sample application loads cart images using code below. In my application product images are store in database. How to modify this code so that images are loaded from database ?

<ul id=“product-list”>


{ %>

foreach (var product in Model)<li>

<a href=“<%= Url.Action(“Details”, “Store”, new { id = product.Contents }) %>”>

<img height=“100” width=“100” alt=“<%= product.Name %>” src=“Content/ProductImages/<%= product.Contents %>.jpg” />

<span><%= product.Name %></span>



<% } %>


The better option will be to store the images on disk and then store the image path in the database

I agree with chieftain. It is better to store images on disk than in the database. That being said, google can help with your question.

Create the following action in the Store controller:

   1. public FileContentResult GetImage( int productId )  
   2. {  
   3.     var product = this._productsRepository.Products.First( x => x.ProductID == productId );  
   4.     return File( product.ImageData, product.ImageMimeType );  
   5. }  

where ImageData is a byte array (byte) contained in a varbinary field and ImageMimeType is the mimetype for each image (image/png, etc)

in your view use it like this

   1. <img src="<%: Url.Action("GetImage", "Store", new { product.ProductID }) %>" />