0

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?

1 Answer 1

1

You have to retrieve every Image separately. A return statement ends the function where you are.

Personally I would save the images on the file system and paths to them in a ImageUrl annotated model property.

  • You can then just make a DisplayFor because the images will be a property of your Model.
  • If you save your image in a Database. The database will get big and slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.