本文介绍了问题使用asp.net从数据库显示图像MVC 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与从数据库显示图像的麻烦。我想保存图像的方法工作,因为我在DB看到VARBINARY领域有一定的价值,并且图像类型是正确的。图像还大小。但是,当我想显示产品形象我没有得到任何东西。只是空格..这里是我的code ...

I'm having trouble with displaying image from db. I think that method for saving image is working, because I see in DB that varbinary fields have some value, and that image type is correct. Also the size of image. But when I want to display image for product i don't get anything. Just blank space.. here is my code...

public byte[] GetImage(int productID)
    {
        Product product = products.GetByID(productID);

        byte[] imageData = product.ImageData.ToArray();

        return imageData;
    }

这code是在我的控制器。二是从视图中code:

That code is in my controller. Second is code from view :

<% if (product.ImageData != null) { %>
    <img src='/product/getimage/<%= Html.Encode(product.ID) %>' alt=""/>
    <% } %>

我想在这里发现堆栈溢出的一些解决方案,每个人都像这样做,但它为他们工作。我没有,为什么不显示图像的任何想法。当我看着网页源$ C ​​$ c。在调试我有:

I tried some solutions found here on stack overflow, and everyone do it like this, but it's working for them. I dont have any idea why images aren't displayed. When i look at source code of page at debugging i have :

<img src='/product/getimage/18' alt=""/>

我使用.NET 4.0,MVC 2,VS 2010 ...在此先感谢

I'm using .net 4.0, MVC 2, VS 2010... Thanks in advance

推荐答案

我的猜测是,你有一个路由问题。如果url /产品/的getImage / 18 应当为你的行动工作,你需要有一个看起来像这样的路线:

My guess is that you have a routing issue. If the url /product/getimage/18 should work for your action you need to have a route that looks something like this:

routes.MapRoute("ProductImage",
    "product/getimage/{productID}",
    new { controller = "Product", action = "GetImage", productID = "" }
);

要确认这一点,你应该使用并在您检查行动网选项卡(或设置一个断点,看看如果在加载页面就被击中)。

To confirm this you should use firebug and check the "net" tab (or set a breakpoint in your action and see if it gets hit when you load the page).

我也建议使用构建在助手来生成网址(当时这种问题不会发生)。取而代之的的src ='/产品/的getImage /&LT;%= Html.En code(product.ID)%GT; 你可以写 SRC ='&LT;%= Url.Action(的getImage,产品,新{=的productID} product.ID)%GT;

I would also recommend using the build in helpers to generate your urls (then this kind of problem will never happen). Instead of src='/product/getimage/<%= Html.Encode(product.ID) %>' you can write src='<%=Url.Action("GetImage", "Product", new { productID = product.ID })%>'

这篇关于问题使用asp.net从数据库显示图像MVC 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:23