2014-10-31 44 views
0

這是我的控制器操作如何在視圖中渲染(圖像)來自模型的數據?

public ActionResult ViewImage(int? productId){ 

      var image = (from x in db.Images 
          where (x.ProductId == productId) 
          select x).ToList(); 
      return View(image); 
     } 

這就是我的觀點

@model 
@{ 
    ViewBag.Title = "ViewImage"; 
} 

<h2>Uploaded pictures</h2> 
<div> 
<br> 
     <img height="300" width="350 " src="@Model" /> 
</div> 
<div> 
    <br> 
    @Html.ActionLink("Back to Index","Index","Products") 
</div> 

我不知道我有什麼@model後放。我試圖把類型的圖像,但不工作!

回答

0

您需要發送模型的類型

@model List<Images> 
+0

剃刀下劃線圖像是一個錯誤!並且我得到錯誤:無法找到類型或名稱空間名稱'Images'(您是否缺少using指令或程序集引用?) – 2014-10-31 20:49:20

+0

只需添加名稱空間! '@model List ' – 2014-10-31 20:51:41

0
Add following property to the model class and add images to it. 


public IEnumerable<HttpPostedFileBase> AttachImages { get; set; } 
0

嘗試,而不是使用VAR圖像ViewBag.Image:

public ActionResult ViewImage(int? productId){ 
      Viewbag.Image image = (from x in db.Images 
         where (x.ProductId == productId) 
         select x).ToList(); 
      return View(image); 
} 

現在,在您的視圖:

@{ 
    ViewBag.Title = "ViewImage"; 
} 

<h2>Uploaded pictures</h2> 
<div> 
<br> 

@foreach(var image in Viewbag.Image) 
{ 
     <img height="300" width="350 " src="@image" /> 
} 
</div> 
<div> 
    <br> 
    @Html.ActionLink("Back to Index","Index","Products") 
</div> 

希望這會有所幫助

0

你應該有一個控制器的行動,在圖像流的響應:

public ActionResult Image(int imageId) 
{ 
    var image = db.Images.SingleOrDefault(x => x.Id == imageId); 
    if (image == null) 
    { 
     return HttpNotFound(); 
    } 

    byte[] imageData = image.Data; // or whatever byte[] property you have 
    string contentType = "image/jpg"; // or if you have stored the content type in your DB simply assign it to image.ContentType 
    return File(imageData, contentType); 
} 

OK,有了這個方便的方法,你可以更新您的看法:

@model IList<WebApplication1.Image> 

<h2>Uploaded pictures</h2> 
<div> 
    @foreach(var image in Model) 
    { 
     <img height="300" width="350 " src="@Url.Action("Image", "SomeController", new { imageId = image.Id })" /> 
    } 
</div> 

注意如何src圖像的屬性指向我們先前實現的控制器動作,它將獲取圖像並將其傳輸到響應。