2012-10-22 47 views
0

如何在數據庫中顯示MVC4中的圖像。如何使用linq過濾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:在控制器retreive圖像價值分配,它在字節數組,並返回到這樣的視圖。

 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 desending)像購物車。

任何人都可以給我解決方案嗎?

回答

1

你必須單獨檢索每個圖像。 return語句結束了你所在的函數。

就我個人而言,我會將文件系統上的圖像和路徑保存到ImageUrl帶註釋的模型屬性中。

  • 然後,您可以製作一個DisplayFor,因爲這些圖像將是您的模型的屬性。
  • 如果將圖像保存在數據庫中。數據庫會變得很大而且很慢。