CodexBloom - Programming Q&A Platform

Visual Studio 2022 - Razor Pages Not Rendering Correctly with JavaScript Interop in ASP.NET Core 7.0

πŸ‘€ Views: 79 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
asp.net-core razor-pages javascript visual-studio C#

I'm dealing with Does anyone know how to I'm prototyping a solution and I'm relatively new to this, so bear with me. I am experiencing an scenario where my Razor pages in an ASP.NET Core 7.0 application are not rendering correctly when I try to use JavaScript interop to manipulate the DOM. My setup involves a basic Razor page that is supposed to update a section of the page when a button is clicked. However, the changes are not reflected in the UI, and I encounter an behavior in the console that says `Uncaught (in promise) behavior: want to read properties of null (reading 'innerHTML')`. I have tried several approaches to troubleshoot this, but I need to seem to resolve the scenario. Here’s a simplified version of my Razor page code: ```razor @page @model MyApp.Pages.IndexModel @{ ViewData["Title"] = "Home page"; } <h1>Hello, World!</h1> <div id="result"></div> <button id="update">Update Content</button> @section Scripts { <script> document.getElementById('update').addEventListener('click', async function () { const resultDiv = document.getElementById('result'); // Simulating a call to .NET method const updatedContent = await DotNet.invokeMethodAsync('MyApp', 'GetUpdatedContent'); resultDiv.innerHTML = updatedContent; }); </script> } ``` On the .NET side, I have the following method in my Razor Page Model: ```csharp using Microsoft.AspNetCore.Mvc.RazorPages; using System.Threading.Tasks; namespace MyApp.Pages { public class IndexModel : PageModel { public async Task<string> GetUpdatedContent() { await Task.Delay(1000); // Simulate async work return "Content updated!"; } } } ``` I've confirmed that the method `GetUpdatedContent` is being called, but it seems that the JavaScript is trying to access the `result` div before it exists in the DOM. I also tried using `window.onload` to ensure that my script runs after the DOM is fully loaded, but the scenario continues. I checked the Network tab, and the response from the .NET method appears to be correct. Any insights on why the updates are not rendering, or how to handle the DOM elements properly would be greatly appreciated. For context: I'm using C# on Windows. This is part of a larger REST API I'm building. Could someone point me to the right documentation? This is my first time working with C# latest. Any feedback is welcome!