I have a sample I'm building, that's using the Northwind database. I have a view in which I show all the products for a specifc category and use a ul to generate items with an image and the products name and price.
I have used the code here, http://blogs.msdn.com/b/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx .
And have gotten to the point that if I right-click an image on my page I get the follow for the image url.
This is the action method I provided, which just takes the Categores ID. /image/show/1
My action method in my ImageController is as follows:
//
// 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);
}
Note: Picture is a byte[]
I then call it in my view like this. (product is the Model for my view)
But I still can't get the image to be displayed.
Change action
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);
}
and send a product instance to view and try this in View
<img src="<%: Url.Action("Show","Image",new { id = Model.Category.CategoryID }) %>" />
Try to use this method instead:
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);
}
This should be basic approach if you don't use that extension. If this works the error is in extension if this doesn't work the error is somewhere else - probably in routing. Also check Gustav's answer!
I'm not sure if that is the problem you have, but I always capitalize the action and controller names:
<%= Url.Action( "Show", "Image", new { id = product.Category.CategoryID } ) %>
Turns out I had to use an anoynomus type ' so that the route was /Image/Show/1, instead of /Image/Show?CategoryID=1. That and of course needed to update the images in Northwind from bitmap to Jpeg.
精彩评论