Asp.net-Mvc-3
在 Razor/MVC3 中顯示來自 db 的圖像
我在數據庫中有一個表,其中包含以下內容:- CountryID、CountryName 和 CountryImage。
現在我正在嘗試在索引中顯示圖像,並且在視圖中有以下內容:-
<td> @if (item.Image != null) { <img src="@Model.GetImage(item.Image)" alt="@item.CountryName"/> }然後在 ViewModel 我有: -
public FileContentResult GetImage(byte[] image) { if (image != null) return new FileContentResult(image, "image/jpeg"); else { return null; } }但是我無法正確看到圖像。
我究竟做錯了什麼?
提前感謝您的幫助和時間
更新
好的所以我在視圖中實現了以下內容:-
<td> @if (item.Image != null) { <img src="@Url.Action("GetImage", "CountryController", new { id = item.CountryID })" alt="@item.CountryName" /> } </td>在 CountryController 中:-
public ActionResult GetImage(int id) { var firstOrDefault = db.Countries.Where(c => c.CountryID == id).FirstOrDefault(); if (firstOrDefault != null) { byte[] image = firstOrDefault.Image; return File(image, "image/jpg"); } else { return null; } }但是當我嘗試調試程式碼時,ActionResult GetImage 沒有被命中
兩種可能。
編寫一個控制器操作,而不是給定圖像 id 將返回此圖像:
public ActionResult GetImage(int id) { byte[] image = ... go and fetch the image buffer from the database given the id return File(image, "image/jpg"); }然後:
<img src="@Url.Action("GetImage", "SomeController", new { id = item.Id })" alt="@item.CountryName" />顯然,現在在您的初始模型中,您不需要該
Image屬性。這將隨後在負責該操作的控制器操作中檢索。另一種可能性是使用數據 URI 方案將圖像嵌入為 base64 字元串,但它可能不會被所有瀏覽器廣泛支持:
<img src="data:image/jpg;base64,@(Convert.ToBase64String(item.Image))" alt="@item.CountryName" />在這種情況下,您不需要控制器操作,因為圖像作為 base64 字元串直接嵌入到您的標記中。