Mapping byte [] of an array image from a database in a detail page template using ASP.NET MVC

When I try to display an image of the byte [] array inside the Details page template using:

public FileContentResult RenderPhoto(byte[] photo) { // var array = (byte[])Session["photo"]; // return File(array, "image/jpeg"); return File(photo, "image/jpeg"); } <img src="@Url.Action("RenderPhoto", Model.Photo)"/> 

The photo is null.

If I store student.Photo in a session:

 // // GET: /Student/Details/5 public ViewResult Details(int id) { Student student = db.Students.Find(id); Session["photo"] = student.Photo; return View(student); } 

and try to display the image getting the value from the session (commented out lines above), it works.

Why do I get a null value in the first case?

After the student transitions to a view in ViewResult Details(int id) , Model.Photo no longer store this value?

+3
database image asp.net-mvc
source share
2 answers

Why do I get a null value in the first case?

You cannot pass an array of bytes to the server in the <img> . The <img> simply sends a GET request to the assigned resource. The correct way to do this is to use id:

 <img src="@Url.Action("RenderPhoto", new { photoId = Model.PhotoId })" /> 

and then:

 public ActionResult RenderPhoto(int photoId) { byte[] photo = FetchPhotoFromDb(photoId); return File(photo, "image/jpeg"); } 
+11
source share

First of all

 Url.Action("RenderPhoto", Model.Photo) 

Does not work, Model.Photo (presumably your byte array) will be considered as an object for determining route values. It will generate a route with the public properties of the Array object, possibly line by line

 ?IsFixedSize=true&IsReadOnly=false&Length=255 

This will be a pretty useless URL. When the page loads in the browser, the browser requests this image by calling your RenderPhoto method, but there is no parameter called a photograph, so the binding will fail, and even if there was a parameter called a photograph (AFAIK) in DefaultModelBinder to create an array of bytes from a string, so the photo is null.

What you need to do is pass an anonymous object with the Id property to Url.Action

 Url.Action("RenderPhoto", new { Id = Model.PhotoId }) 

This will be converted to a query, perhaps along the lines of the following (but it depends on your routes)

 /xxx/RenderPhoto/25 

And then you will need to return the data for the photo to your RenderPhoto method

Martin

+1
source share

All Articles