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++;
}
>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
- Add a JavaScript function in your
_Host.cshtmlorindex.html:<script> window.logToConsole = (message) => { console.log(message); }; </script>
like so
- 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
F12orCtrl+Shift+Ito 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.