开发者

MVC: Displaying an Image in a form with other form data from database

The question as to how to display an image, stored as an image in the database and as a byte array in cod开发者_如何转开发e, has been answered several times (e.g., Display image from database in asp mvc), but what if you want to display the image in the context of a form. That is, I have an object that has several fields, one of which is an image. I have got it working where the user can upload the image and it gets stored as part of the save process, along with the rest of the object fields. But how do I send it back out (and ideally display it) with the rest of the data to populate the Edit form? All of the solutions I've seen have some sort of ShowImage action that takes an Id and retrieves the image and streams it to the response. However, I don't see how this works in this scenario.

The only thing I can think of is to populate the form and then use jquery to retrieve the image and display it in the form, but that's a lot of extra traffic that seems unnecessary.

Anyone know how to do this?

Thanks.


I would make a controller action that just servers up your image.

Then in your view that displays the image and other data, just pass it the URL to correct action that will serve up the image with the rest of view data. Then use an img tag to display your image by making the view data URL as the src. The img will call the URL and fetch it for you.

So to break it down you have two controller actions like GetImage and FormDetails or something and the GetImage is only used to fetch images from your DB and return the byte array as an image response (you could also do some server side checking for security here). The FormDetails action would get all the data including the URL to your image only and put it all together.

EDIT based on your comment: To get around the two calls you could implement some caching... when it is uploaded you could store it temporarily like:

// Cache it for 5 mins (and keep it cached until it has not be accessed for 5 mins.
System.Web.HttpContext.Current.Cache.Insert("YourImage" + imageID.ToString(),
    yourImage, null, System.Web.Caching.Cache.NoAbsoluteExpiration, 
    new TimeSpan(0, 5, 0)); 

Then in your controller action that serves up the image you could check to see if the value exists in the cache first before doing the DB call which will save you the second trip in most cases if your scenario is as described:

if (System.Web.HttpContext.Current.Cache["YourImage" + imageID.ToString()] == null)
{
    // get image from DB
}
else
{
    // image is cached so serve it up!
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜