How to display images in MVC4 from database.
Step 1: In my code, retrieve the data and place in array class.
public class ImageTable
{
public string ImageId { get; set; }
public string CategoryId { get; set; }
public byte[] Image { get; set; }
}
public class DataAcceess
{
public ImageTable[] GetImages()
{
ImageTable[] Images = null;
SqlConnection Conn = new SqlConnection("Data Source=;Initial Catalog=;UserID=;Password=;");
Conn.Open();
//SqlCommand Cmd = new SqlCommand("Select [Product ID],ImageView1 From Cpecial_Image_tbl", Conn);
SqlCommand Cmd = new SqlCommand("Select b.[Category ID],a.[Product ID], a.[ImageView1] from Cpecial_Image_tbl as a inner join [Cpecial_Product_tbl] as b ON a.[Product ID]=b.[Product ID]", Conn);
SqlDataReader Reader = Cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(Reader);
Images = new ImageTable[dt.Rows.Count];
int i = 0;
foreach (DataRow Dr in dt.Rows)
{
Images[i] = new ImageTable()
{
ImageId = (string)Dr["Product ID"],
CategoryId = (string)Dr["Category ID"],
Image = (byte[])Dr["ImageView1"]
};
i = i + 1;
}
Conn.Close();
return Images;
}
Step 2: In controller retreive the image value assign, it in byte array and return to the view like this.
public ActionResult Index(string id)
{
// var image = db.Categories.First(m => m.CategoryID == id).Picture;
DataAcceess objContext = new DataAcceess();
//byte[] Image = (from a in Images select a.Image.ToArray());
byte[] a;
foreach (var item in objContext.GetImages())
{
a = item.Image;
return File(a, "Image/jpg");
}
return View();
}
Step 3: I added the tag in view like this this will show only one image.
I want to show all the the images, and also manipulate the image with respect to the Filters
(sorting ascending , desending with catagoryId) like in shopping cart.
Could any one give me the solution?