dotnet / razor

Compiler and tooling experience for Razor ASP.NET Core apps in Visual Studio, Visual Studio for Mac, and VS Code.
https://asp.net
MIT License
501 stars 191 forks source link

Issue: preventDefault Not Working in Blazor Interactive WebAssembly Events in .NET 8 #11123

Open Xilmirius opened 3 hours ago

Xilmirius commented 3 hours ago

Here's a more polished version of your GitHub issue:


Issue: preventDefault Not Working in Blazor Interactive WebAssembly Events in .NET 8

Description
I'm encountering an issue with the preventDefault modifier on Blazor events in .NET 8 Interactive WebAssembly. Specifically, preventDefault is not functioning as expected, causing form submissions to reload the page whenever I press "Enter" in an input field.

This behavior worked correctly in .NET 7. However, in .NET 8, it fails to prevent default behavior in multiple scenarios.

Checklist

Reproduction Steps
I reproduced this issue in a fresh Blazor WebAssembly project with the following code:

<form novalidate autocomplete="off">
    <input value="Hello World" onkeypress:preventDefault onkeypress="@KeyPress" />
    <button type="button" onclick="@Click">
        Click me
    </button>
</form>

@code {
    private void KeyPress(KeyboardEventArgs args)
    {
        if (args.Key == "Enter") Console.WriteLine("Hello");
    }

    private void Click() => Console.WriteLine("Click");
}

Observed Behavior
When pressing "Enter" within the input field, the onkeypress:preventDefault modifier does not prevent the default behavior. The page reloads each time the "Enter" key is pressed.

I also attempted the following variations, but they yielded the same issue:

<input value="Hello World" onkeypress="@KeyPress" onkeypress:preventDefault="true" />

The only workaround I found was to use raw JavaScript:

<input value="Hello World" onkeypress="event.preventDefault();" />

However, this method is not viable for attaching C# event handlers, as it bypasses Blazor's event handling entirely.

Expected Behavior
The onEvent:preventDefault modifier should prevent default behavior (e.g., form submission on "Enter") as it did in .NET 7.

Additional Context
.NET 8 Blazor WebAssembly in Interactive mode. Base on Documentation

Xilmirius commented 3 hours ago

I also try using onkeyup and onkeydown but have non result either.

I found that onkeydown i need to press twice to reload the page

Further more I'm using <form novalidate autocomplete="off" onsubmit="event.preventDefault()"> to avoid the reset