2014-10-31 46 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图像的属性指向我们先前实现的控制器动作,它将获取图像并将其传输到响应。