使用asp.net MVC 2显示图像的问题 [英] Problem with displaying image from DB using asp.net MVC 2
问题描述
我在从db显示图片时遇到问题。我认为保存图像的方法是工作,因为我在DB中看到varbinary字段有一些值,并且该图像类型是正确的。还有图像的大小。但是,当我想显示产品的图像我没有得到任何东西。只是空格..这是我的代码...
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;
}
代码在我的控制器中。第二个代码来自视图:
That code is in my controller. Second is code from view :
<% if (product.ImageData != null) { %>
<img src='/product/getimage/<%= Html.Encode(product.ID) %>' alt=""/>
<% } %>
我尝试了一些在堆栈溢出的解决方案,每个人都这样做,他们。我不知道为什么图像不显示。当我看看调试页面的源代码有:
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 / product / 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 = "" }
);
要确认,您应该使用 firebug ,并检查网络标签(或在您的操作中设置断点,看看是否在加载网页时被点击)。
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).
我也建议使用build在helpers生成你的urls(然后这种问题永远不会发生)。除了 src ='/ product / getimage /<%= Html.Encode(product.ID)%>'
,您可以写 src = '<%= Url.Action(GetImage,Product,new {productID = product.ID})%>'
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显示图像的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!