Razor pages .Net core displaying a base64 image from Page Model

Viewed 440

I am new to .Net Core and Razor pages and have hit a bit of a problem. I am sure this is pretty simple but haven't been able to get the wright answer yet. I have images stored in my database (base64 encoded):

enter image description here

I am in the Code behind IndexModel:

enter image description here

Within this class I have implemented this bound model:

enter image description here

And am attempting to pass the Base64 image string to the Page:

enter image description here

And initially attempted to display the image:

enter image description here

However, everyone would probably already know that this doesn't work. Im guessing the model I am passing is only accessible though certainly htm helper tags and an img src isn't one of them.

Is there a more standard way of getting the result I am after using this model or any other means? I have taken a look at ViewBag but couldn't get this to work either. If anyone is able to offer an example I would be forever grateful!

2 Answers

So summary what worked for you:

Controller:

[ViewData]
public string ImageString { get; set; }

public async Task LoadAsync(IdentityUser user)
{
    var appUser = await _userManager.Users.Include(x => x.ApplicationUserImage).SingleAsync();
    Username = appUser.UserName;

    string imageBase64Data = Convert.ToBase64String(appUser.ApplicationUserImage.ImageData);
    string imageData = string.Format("data:image/jpg;base64, {0}", imageBase64Data);

    this.ImageString = imageData;
}

View:

<div class="form-group">
    <img id="UserImage" src="@Model.ImageString" alt="your image" />
</div>
Related