Problem with displaying image from DB using asp.net MVC 2

后端 未结 5 1815
情话喂你
情话喂你 2021-01-17 00:41

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

相关标签:
5条回答
  • 2021-01-17 00:55

    I needed to register routes in my global.cs file like Mathias suggested.

    Also i needed to modify action in my controller to this :

    public FileContentResult GetImage(int productID)
        {
            Product product = products.GetByID(productID);
    
            return File(product.ImageData.ToArray(), product.ImageMimeType);
        }    
    

    I wish thank you all for your fast answers...

    0 讨论(0)
  • 2021-01-17 00:57

    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).

    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 })%>'

    0 讨论(0)
  • 2021-01-17 01:00

    Try to change you method to:

    public void GetImage(int productID)
    {
        Product product = products.GetByID(productID);
    
        Response.ContentType = "image/jpeg";
        Response.BinaryWrite(product.ImageData.ToArray());
    
    }
    
    0 讨论(0)
  • 2021-01-17 01:16

    I'm not much of an expert on MVC yet - but from what I can see, I think your GetImage function needs to be an Action Method inside your controller, so it'll need to return an ActionResult?

    You'll probably need to set the Content-Type header in the response, too.

    This guy looks like he knows what he's talking about...

    http://blogs.msdn.com/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx

    0 讨论(0)
  • 2021-01-17 01:16

    You have:

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

    Normally i'd say an image tag looks like this:

    <img src='/product/getimage/18.jpg' alt=""/> 
    
    0 讨论(0)
提交回复
热议问题