I am currently stuck with this problem of displaying an image using HtmlHelper class.
Here is what i have.
I have a custom HtmlHelper class which supposed to display an image:
public static string Images(this HtmlHelper helper, ......){
var writer = new HtmlTextWriter(new StringWriter());
byte[] bytearray = ... // some image byte array retrieved from an object.
// begin html image tag - this is where the problem is
writer.AddAttribute(HtmlTextWriterAttribute.Src, url.Action("GetPhoto", "Clinical", new { image = bytearray }));
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
// end of image tag
return writer.InnerWriter.ToString();
}
So what i tried to do above is to inject a Url.Action into the img source attribute.
I have a controller “GetPhoto” that is suppsoed to handle that bytearray and return an image.
public FileContentResult GetPhoto(byte[] image)
{
return File(image, "image/jpeg");
}
I managed to get to the controller, but image shows as null. Is there a way around it ? or maybe an even better way to do this? Your help will be very much appreciated, Thanks!
There are some problems with your controller action. It expects to pass the image as a byte array. In your helper class you are trying to generate an
imgtag pointing to this controller action and passing a byte array but this won’t work because you cannot pass byte arrays using GET requests. You need to change this controller action so that instead of accepting a byte array it takes for example some identifier that allows you to fetch the image and write it to the output stream. Then your html helper will pass this identifier when generating theimgtag.And your helper:
Which could be used in your view: