andrewb
andrewb

Reputation: 3095

Outputting HTML without using MVC helper

I have one view which outputs a list of data from a database, one of those fields is an image which is uploaded via my website. I output the image like so:

<img src='@item.ToBase64ImageString(@item.FileData)' />

And in my model I have:

    public string ToBase64ImageString(byte[] data)
    {
        return string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(data));
    }

I have another view where it's purpose is just to show details of the selected item (Controller/Details/id) and I would like to show the image in this view too.

I am unable to use the code from above as I do not have an individual item in @item - I have @model but for some reason this approach does not work.

Here is the details view:

@model Models.Tier

@Html.DisplayNameFor(model => model.FileData)
<img src="@Html.DisplayFor(model => model.ToBase64ImageString(model.Bild))" />

In short, how can I output HTML for a model field without using the helpers?

Upvotes: 1

Views: 35

Answers (1)

Shyju
Shyju

Reputation: 218722

You can create an extension method on byte array and use that wherever needed

public static class MyByteArrayExtensions
{
    public static string ToBase64(this byte[] data)
    {
        return string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(data));
    }
}

In your view,

<img src="@Model.Bild.ToBase64()" />

Upvotes: 2

Related Questions