0

I stored few images in sql server database in binary format and then retrieved them back and im able display as image but my requirement is that i should display all the images as gallery from database but im able to display only the 1st image as gallery...

my problem is in my controller code as in the forloop its returning file for the first loop itself and view is displayed

Controller

public ActionResult DislpayAllImage()
{
    DataSet dsa = new DataSet();
    dsa = objImage.getAllImages();
    DataTable dt = new DataTable();
    dt = dsa.Tables[0];
    if (dt != null)
    {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Byte[] image = (Byte[])dt.Rows[i]["UsImage"];
            return File(image, "image/jpg");
        }
    }

    return View();
}

View

@foreach( var image in ViewData.Images )
{
    <img src="@Url.Action("DislpayAllImage", "Home",new { id = image.ImageID })" />
}
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
colors bright
  • 107
  • 1
  • 3
  • 18

3 Answers3

1

MVC controller can return only once! Try it:

ViewData.Images = new List<byte[]>();
for (int i = 0; i < dt.Rows.Count; i++)
{
   dt.Rows.Add((Byte[])dt.Rows[i]["UsImage"]);
}
Slovo
  • 212
  • 2
  • 11
0

Well first of all you can't do return File(image, "image/jpg"); in your for loop as it will return the first image as you wrote in your explanation.

So instead of returning in the for loop how about you collect the images and return the list?

List<File> fileList = new List<File>();
for (int i = 0; i < dt.Rows.Count; i++)
        {
            Byte[] image = (Byte[])dt.Rows[i]["UsImage"];
            fileList.Add(File(image, "image/jpg"));
        }

and then return your view with the images as a parameter.

return View(fileList);
Moriya
  • 7,750
  • 3
  • 35
  • 53
0

This is just a notion, not entire code is properly implemented and tested.

[HttpGet]
public ActionResult Index()
{
   ViewData["count"]=..count the number of rows which have binary image data
}

Then in your view get the view data and loop through

@for(int i=0;i<=ViewData["count"];i++)
{
   <img src="@Url.Action("DislpayAllImage", "Home",new { id = i})" />
}

Then in your controller

[HttpPost]
public ActionResult Index(int id)
{
        DataSet dsa = new DataSet();

        dsa = objImage.getUserImage(id);
        Byte[] imagedata = (Byte[])dsa.Tables[0].Columns["MyImage"];
        return File(imagedata, "image/jpg");

}

Hope it helps

Karthik Chintala
  • 5,465
  • 5
  • 30
  • 60