Orion Rigel Orion Rigel - 1 month ago 15
ASP.NET (C#) Question

Displaying Image in MVC

I am trying to display an Image from Database. But, I am getting the following error.


The best overloaded method match for System.Web.Mvc.UrlHelper.Content(string) has some invalid arguments.


Here is my code:

<table>
<tr>
<td>
Category ID
</td>

<td>
Category Name
</td>

<td>
Category Image
</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.CategoryID</td>
<td>@item.CategoryName</td>
<td><img src="@Url.Content(item.CategoryImage)" /></td>

</tr>
}
</table>

Answer

This is code that I use :

    private static string ImageByteToBase64ImageTag(byte[] array)
    {
        string base64 = Convert.ToBase64String(array);
        return "<img class=\"img-responsive center-block\" src=\"data:image/png;base64," + base64 + " \"  />";
    }

In this case, it would be much easier to work with the image as a base64 image. My code is pretty straight forward but all you have to do is pass an array of the image and get a base64 string. You can even return the image via JSON if you format it right. You can return just the following portion in a ViewBag or Model:

ViewBag.ImageData = "data:image/png;base64," + base64String

And in your html

  <img src="@Html.Raw(ViewBag.ImageData)" />

Or in your model, just make a string property for the image.

Comments