Hey everyone! I’m stuck trying to use my MVC model data in JavaScript to generate a QR code. I’m using the qrcode library by davidshimjs.
Here’s what I’ve tried:
var sessionId = '@Model.CurrentSessionId';
var url = 'https://example.com/Game/Start/' + sessionId;
new QRCode(document.getElementById('qrcode'), url);
But the QR code isn’t showing up. With a hardcoded URL, everything works fine. I’ve attempted different methods including using @Html.Raw() and template literals, but nothing seems to work.
Since I can’t set breakpoints in my Razor view, I’m at a loss for how to properly pass the model data to JavaScript. Any suggestions on how to resolve this would be greatly appreciated!
Thanks a lot! My brain is a bit fried from all the troubleshooting.
I’ve faced similar challenges linking Razor model data to JavaScript. Often the issue is related to when the code executes. In my experience, shifting the QR code initialization to run after the DOM is completely loaded usually resolves the problem. For instance, wrapping the QR code generation code in a window.onload event ensures that all page elements, including the one with the ‘qrcode’ id, are available. It’s also useful to inspect the rendered HTML and use console logging to confirm that the sessionId value is correctly injected into your script.
Have you checked if the sessionId is actually being rendered correctly in the JavaScript? One approach I’ve found effective is to output the sessionId to the console for debugging. You could try something like this:
var sessionId = '@Model.CurrentSessionId';
console.log('Session ID:', sessionId);
var url = 'https://example.com/Game/Start/' + sessionId;
new QRCode(document.getElementById('qrcode'), url);
This way, you can verify if the Model data is being correctly passed to your JavaScript. If the sessionId is empty or undefined, that could explain why your QR code isn’t generating. Also, make sure the ‘qrcode’ element exists in your DOM before the script runs. Sometimes, wrapping the code in a DOMContentLoaded event listener can help ensure everything’s in place before execution.
hey mate, have u tried using an ajax call to fetch the sessionId? sometimes razor syntax can be finicky with js. u could make a simple controller action that returns the sessionId as json, then use fetch or $.ajax to grab it. might solve ur problem without the hassle of debugging razor syntax in js. just a thought!