Using Javascript in the Model-View-Controller (MVC) pattern to load images stored as byte

Despite the numerous solutions available on Stack Overflow, I am still unable to get any of them to work...

I am faced with the challenge of setting the "src" attribute of an image tag using a byte array obtained from an ajax call to my controller in JavaScript. This task must be carried out client-side as I am dynamically generating some of the HTML content (not included in the provided example)

Below is the view code:

<div>
<button onclick=" loadFromDb(); ">CLICK ME</button>
<img id="imgFromModel" src="data:image/png;base64,@Convert.ToBase64String(Model.Image)" alt="" />

<img id="imgFromScript" src="#" alt=""/>
</div>

And here is the script snippet:

function loadFromDb() {
    $.ajax({
        url: "/Home/LoadFromDatabase",
        async: true,
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            var base64String = btoa(response.Image);
            $("#imgFromScript").attr("src", "data:image/png;base64," +  base64String);
        }
    });
}

The image successfully loads in the "imgFromModel" tag, but for some reason not in the "imgFromScript" tag. Can anyone guide me on how to set the "src" attribute of an image tag with a byte array retrieved from a controller?

Your assistance would be greatly appreciated.

Answer №1

After hours of experimentation, a restful night's sleep, and some good fortune, I finally cracked the code.

I realized that I needed to introduce a new string property in my model called "ImageBytesAsString" and then set the source to that in my ajax response. Here is how I implemented it...

MODEL:

public byte[] Image { get; set; }
public string ImageBytesAsString { get; set; }

CONTROLLER:

var user = context.Users.FirstOrDefault();
user.ImageBytesAsString = Convert.ToBase64String(user.Image);

JAVASCRIPT:

    $.ajax({
    url: "/Home/LoadFromDatabase",
    async: true,
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        $("#imgFromScript").attr("src", "data:image/png;base64," + response.ImageBytesAsString);
    }
});

VIEW:

<img id="imgFromScript" src="#" alt=""/>

I hope this solution proves useful for someone else facing a similar challenge.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I align rectangles with different heights to display side by side using Javascript?

Currently, I am designing a press page for a website where the headlines/articles are displayed in rectangles. To achieve this layout, I am using the following CSS: .press-blocks{ column-count: 4; column-gap: 2em; padding-left: 10%; padding ...

How can you prevent JQuery AJAX from automatically redirecting after a successful form submission?

Encountered an issue with loading http://example.com/signup.ashx: The redirect from 'http://example.com/signup.ashx' to '' was blocked by the CORS policy. This is due to the absence of 'Access-Control-Allow-Origin' header on t ...

Generate images in real-time based on model element properties

I have a ViewModel that includes a collection of strings that I intend to use for dynamically displaying images on a Razor view. public List<string> States { get; set; } = new List<string>() { "ACT", "NSW", "NT", ...

Issues with Imported Routes Not Functioning as Expected

I am currently working on implementing routing in my Angular 2 project. All the components are functioning properly, but I encounter an error when I include 'appRoutes' in the imports section of app.module.ts. An unexpected TypeError occurs: C ...

Having difficulty generating a footer for a page that includes a Material-UI Drawer component

Looking to create a standard full-width footer at the bottom of my page, I need help with the implementation. Utilizing the "Permanent drawer" from Material-UI Drawer for reference here. If you're interested in experimenting with it, CodeSandbox link ...

uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance: struct UserData { uWS::WebSocket<true, uWS::SERVER> *ws; bool logged_in = false; ID user_id; }; uWS::SSLApp() .ws<UserData>( ...

Tips for incorporating fading text and a CTA into your content block

I am looking to protect the full content of my blog posts and allow access only to subscribed members. I want readers to see just a glimpse of the article before it disappears, prompting them to take action with a Call to Action (CTA) like in the fading te ...

Problem-solving modal disappearance

In my current project, I am working on a feature that involves displaying a dropdown modal after 3 minutes on the page. The modal includes an input field where users can enter digits, and upon clicking 'save', the modal should hide. Everything se ...

What is the best way to make the current year the default selection in my Select control within Reactive Forms?

Hey there! I managed to create a select element that displays the current year, 5 years from the past, and 3 years from the future. But now I need to figure out how to make the current year the default selection using Reactive Forms. Any ideas on how to ac ...

Encountering an issue with the SSR module evaluation despite having SSR disabled in Svelte Kit

I needed a specific route in my app to not be server-side rendered. This can be achieved by setting export const ssr = false in the module script or configuring ssr: false in the svelte.config.js, as outlined in the Svelte documentation. Despite disabling ...

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

button that decreases in size when clicked on

Currently, I am dealing with an element that functions as a button using a combination of Javascript and CSS. To better illustrate the issue, I will simplify the example by removing unnecessary details. The main problem lies in the fact that when this elem ...

Anomalous Snackbar and Alert Interactions

Why am I getting an error with this code snippet: import Snackbar from "@mui/material/Snackbar"; import MuiAlert from "@mui/material/Alert"; const Alert = ({children}) => <MuiAlert>{children}</MuiAlert> <Snackbar ope ...

Making an Ajax request using jQuery to retrieve content in the application/x-javascript format

Can anyone help me figure out how to retrieve the content of "application/x-javascript" using a jQuery Ajax call? I keep getting null content and I'm not sure why. This is what I have been attempting so far: $.ajax({ dataType: "json", ...

Is it possible to attach an onclick event to modify a data point in Chart.js?

Currently using chartjs for a small project and facing some challenges with editing data points. Is there a built-in function in this library that allows me to bind an onclick event for displaying a pop-up and removing the point? This is what I am lookin ...

Discover the secret to loading multiple Google charts simultaneously, despite the limitation that Google charts typically only allow one package to load at a time

I currently have a pie chart displaying smoothly on my webpage, but now I am looking to add a treemap as well. The code snippet for the treemap includes the package {'packages':['treemap']}. It has been stated that only one call should ...

I have to display a pop-up message box after selecting an option from a dropdown menu that fulfills a set of conditions

I am attempting to display a pop-up message when a selection is made on a dropdown menu that meets specific criteria. The dropdown list is generated from a coldfusion output query. I am relatively new to JavaScript, so I may be missing something in my code ...

Tips for preventing the loading of multiple local versions of jQuery

I have been struggling to prevent redundant loading of my local version of jQuery and jQuery UI due to the continuous Ajax pulls on the pages, which trigger a reload by jQuery each time. The specific jQuery files I am currently loading are: <script s ...

Guide to dynamically add tr element using CSS to a table

While using the $.each function in jQuery, I am retrieving data and adding it to a table in the following manner: $.each(segment, function (index, innerSegment) { var tr; tr = $('<tr/>'); tr.append("<td>" + segment[i].Airline.Air ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...