如何从数据库中显示 MVC4 中的图像。
第 1 步:在我的代码中,检索数据并放入数组类中。
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;
}
第2步:在控制器中检索图像值分配,它在字节数组中并像这样返回到视图。
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();
}
第 3 步:我像这样在视图中添加了标签,这将只显示一张图像。
我想显示所有图像,并
像在购物车中一样处理与过滤器相关的图像(升序排序,使用 catagoryId 降序)。
谁能给我解决方案?