Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Button work only on variables .NET 8 Blazor Web Assembly

I tried to modify my "Counter.razor" code with a Console.WriteLine, but nothing is printed inside of the console, and the counter get the +1.

I have my @rendermode InteractiveWebAssembly and can’t set it to @rendermode InteractiveServer because I will need it for the future

private void IncrementCounter()
{
    Console.WriteLine("ouiii");
    counter++;
} 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In Blazor WebAssembly, Console.WriteLine logs to the browser’s developer console, not the server console. Here’s how you can log messages effectively:

Using JavaScript Interop

  1. Add a JavaScript function in your _Host.cshtml or index.html:
    <script>
        window.logToConsole = (message) => {
            console.log(message);
        };
    </script>
    

like so

  1. Call this function from your Blazor component:
    @inject IJSRuntime JSRuntime
    
    <button @onclick="IncrementCounter">Click me</button>
    
    @code {
        private int counter = 0;
    
        private async void IncrementCounter()
        {
            counter++;
            await JSRuntime.InvokeVoidAsync("logToConsole", $"Counter: {counter}");
        }
    }
    

Alternatively… you can:

  • Press F12 or Ctrl+Shift+I to open developer tools.
    or,
  • Go to the "Console" tab to view the messages.

This way, you can log and view messages directly in the browser’s console.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading