2010-08-22 130 views
4

我有一个样本,我正在建设,那是使用Northwind数据库。 我有一个视图,其中显示了特定类别的所有产品,并使用ul生成带有图像和产品名称和价格的项目。如何在asp.net mvc中渲染图像?

我在这里使用了代码http://blogs.msdn.com/b/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx

并且已经到了这样的地步,如果我右键单击我的页面上的图像,我会得到 以下图像url。

这是我提供的操作方法,它只需要分类ID。在我ImageController /图片/显示/ 1

我的操作方法如下:

// 
    // GET: /Image/Show 
    public ActionResult Show(int id) 
    { 
     var category = northwind.AllCategories().Single(c => c.CategoryID == id); 
     byte[] imageByte = category.Picture; 
     string contentType = "image/jpeg"; 

     return this.Image(imageByte, contentType); 
    } 

注:图片是一个byte []

然后我把它在我看来是这样的。 (产品是我认为的型号)

但我仍然无法得到要显示的图像。

+0

导航到操作的URL(/ image/show/1)时图像是否正确显示?如果是这样,那么将图像嵌入到HTML中的方式会有错误。 否则,检查您的方法使用Fiddler2或类似方法返回的数据。 – LorenzCK 2010-08-22 09:57:45

回答

10

变化行动

public FileContentResult Show(int id) 
{ 
    var category = northwind.AllCategories().Single(c => c.CategoryID == id); 
    byte[] imageByte = category.Picture; 
    string contentType = "image/jpeg"; 

    return File(imageByte, contentType); 
} 

和发送产品实例来查看和尝试有鉴于此

<img src="<%: Url.Action("Show","Image",new { id = Model.Category.CategoryID }) %>" /> 
+0

你明白了。感谢您的帮助,只是意识到您确实需要我。 – 2010-08-22 11:33:27

+0

Flippin'真棒! – 2010-10-12 02:00:44

0

我不知道如果这是你有问题,但我一直把握的动作和控制器名称:

<%= Url.Action("Show", "Image", new { id = product.Category.CategoryID }) %> 
+0

我也更新了我的,谢谢。 – 2010-08-22 11:17:48

1

尝试使用此方法代替:

public FileContentResult Show(int id) 
{ 
    var category = northwind.AllCategories().Single(c => c.CategoryID == id); 
    byte[] imageByte = category.Picture; 
    string contentType = "image/jpeg"; 
    return File(imageByte, contentType); 
} 

这应该如果你不使用这个扩展名是基本的方法。如果这有效,错误是扩展,如果这不起作用错误是其他地方 - 可能在路由。同时检查古斯塔夫的答案!

+0

我改变了方法,但仍然没有显示图像。该图像显示的网址为/图像/显示?CategoryID = 1 和我的路线是/产品/浏览/饮料例如 – 2010-08-22 11:18:32

+0

原来我不得不使用anoynomus类型 2010-08-22 11:31:00

0

原来我不得不使用anoynomus型 ',这样的路径是/图像/ Show/1,而不是/ Image/Show?CategoryID = 1。这当然需要将Northwind中的图像从位图更新为Jpeg。