【问题标题】:How can I render an image in asp.net mvc?如何在 asp.net mvc 中渲染图像?
【发布时间】:2010-08-22 09:43:39
【问题描述】:

我正在构建一个使用 Northwind 数据库的示例。 我有一个视图,其中显示特定类别的所有产品,并使用 ul 生成带有图像以及产品名称和价格的项目。

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

并且已经达到这样的程度,如果我右键单击页面上的图像,我会得到 图片网址如下。

这是我提供的操作方法,它只接受类别 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);
    }

注意:图片是一个字节[]

然后我在我看来这样称呼它。 (产品是我认为的模型)

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

【问题讨论】:

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

标签: c# asp.net-mvc model-view-controller


【解决方案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);
}

并发送产品实例以查看并在 View 中尝试

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

【讨论】:

  • 你明白了。感谢您的帮助,刚刚意识到您正是我所需要的。
【解决方案2】:

尝试改用此方法:

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

如果您不使用该扩展程序,这应该是基本方法。如果这可行,则错误在扩展中,如果这不起作用,则错误在其他地方-可能在路由中。还要检查古斯塔夫的答案!

【讨论】:

  • 我改变了方法,但仍然没有显示图像。图片显示的 url 是 /Image/Show?CategoryID=1 ,我的页面路径是 /Products/Browse/Beverages 例如
  • 原来我必须使用匿名类型 ' 这样路由是 /Image/Show/1,而不是 /Image/Show?CategoryID=1。这当然需要将 Northwind 中的图像从位图更新为 Jpeg。谢谢您的帮助。 :)
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多