-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
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
- I have searched for this issue in forums and documentation.
- This issue blocks key functionality.
- The behavior works as expected in .NET 7.
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