我该如何在asp.net mvc中渲染图片?

5
我正在制作一个示例,使用了Northwind数据库。我有一个视图,在其中显示特定类别的所有产品,并使用ul生成带有图像和产品名称和价格的项目。
我在这里使用了代码:http://blogs.msdn.com/b/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx
如果我右键单击页面上的图像,我会得到以下图像url。
这是我提供的操作方法,只需要传递“类别ID” /image/show/1
我的ImageController中的操作方法如下:
    //
    // 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);
    }

注意:Picture 是一个 byte[]
然后我在视图中这样调用它(product 是我的视图模型)
但是我仍然无法显示图片。

当您导航到操作的URL(/image/show/1)时,图像是否正确显示?如果是,则在HTML中嵌入图像的方式存在错误。 否则,请使用Fiddler2或类似工具检查方法返回的数据。 - LorenzCK
4个回答

11

更改操作

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  }) %>" />

明白了,感谢你的帮助,我刚意识到你正好有我需要的东西。 - Carl Weis

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);
}

如果您不使用该扩展,这应该是基本方法。如果这有效,则错误在于扩展;如果这无效,则错误可能在于路由。还要检查Gustav的答案!


我已经更改了方法,但仍然没有显示任何图像。 图像的URL显示为/Image/Show?CategoryID=1,而我的页面路由为/Products/Browse/Beverages,例如。 - Carl Weis
结果发现我必须使用匿名类型<img src='<%= Url.Action("Show", "Image", new {id = product.Category.CategoryID } ) %>',这样路由就是/Image/Show/1,而不是/Image/Show?CategoryID=1。 当然还需要将Northwind中的图像从位图更新为Jpeg格式。感谢您的帮助。 :) - Carl Weis

0

我不确定这是否是你遇到的问题,但我总是将动作和控制器名称大写:

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

0
原来我必须使用一个匿名类型',这样路由就是/Image/Show/1,而不是/Image/Show?CategoryID=1。当然,还需要将Northwind中的图像从位图更新为Jpeg。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接