Skip to content

PreventDefault as a method on Blazor event arguments #45949

@stsrki

Description

@stsrki

We already have a way of preventing events in Blazor, but the problem is that it is very limited. The prevention only works after the event handler is over and the component rendering cycle is finished. This way it is really hard to do any advanced handling on input, like input masking for example. The existing behavior can be seen in the next example.

Existing API

<input value="@name" type="text" @onkeydown="@onKeydown" @onkeydown:preventDefault="@isPreventKey" />

@code {
    private string name { get; set; }

    private bool isPreventKey { get; set; }

    private void onKeydown( KeyboardEventArgs args )
    {
        this.isPreventKey = args.Key == "a";
    }
}

I am aware that we can do the JavaScript-type event handlers, eg. <input onkeydown="do some stuff here" />, but that way, we cannot access any code from C# without additional interop calls.


My proposal is to add the PreventDefault() method on existing event argument classes, eg KeyboardEventArgs, MouseEventArgs, and others. Blazor will somehow internally keep track of the event argument state, and if .PreventDefault(); was invoked the event would be canceled.

Proposed API

<input value="@name" type="text" @onkeydown="@onKeydown" />

@code {
    private string name { get; set; }

    private void onKeydown( KeyboardEventArgs args )
    {
        if ( args.Key == "a"  )
        {
            args.PreventDefault();
        }
    }
}

As far as am aware, we have a similar API to the proposed one already on the navigation. So the use case would be similar.

eg.

private ValueTask OnLocationChanging(LocationChangingContext context)
{
    if (context.TargetLocation == "/counter")
    {
+        context.PreventNavigation();
    }

    return ValueTask.CompletedTask;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Pillar: Complete Blazor Webapi-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing one

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions