fourbeatcoder
fourbeatcoder

Reputation: 1419

Blazor datalist onchange event not firing

I have implemented an onchange in a datalist in my .razor component in my Blazor Server / .NET Core 3.1. application.

In the browser when I select an option from the datalist the OnChanged method does not fire. My break-point in OnChanged is not hit.

I want it to fire and then use OnChanged to populate the <select name="EventsInType">

I have added a <button element to the page with @onclick="OnClicked" as an example of something that works - this does fire and my breakpoint in OnClicked is hit.

Cannot convert method group 'OnChanged' to non-delegate type 'object'. Did you intend to invoke the method?

I would have thought this should be simple enough with Blazor, is there something that I do not understand here?

Here is the code:

@page "/"
@inherits EventDetailsBase
Event Type
<input autoComplete="on" list="EventTypes" placeholder="Search event types..." />
<datalist @onchange="OnChanged" id="EventTypes">
    @foreach (var eventType in EventTypes)
    {
        <option value="@eventType.Name">@eventType.Name</option>
    }
</datalist>

<select name="EventsInType">

</select>

<button class="btn btn-primary" @onclick="OnClicked">
    Click Me
</button>

@code {
    private void OnClicked(MouseEventArgs e)
    {
        var test = "";
    }

    private void OnChanged(ChangeEventArgs args)
    {
        //POPULATE HTML SELECT "EventsInType" HERE
    }
}

The base class is probably irrelevant but here it is anyway:

    public class EventDetailsBase : ComponentBase
    {
        [Inject]
        public IMyService MyService { get; set; }
        public List<EventType> EventTypes { get; set; } = new List<EventType>();

        protected override async Task OnInitializedAsync()
        {
            EventTypes = await MyService.GetEventTypes();

        }

        public void GetEventsByType(ChangeEventArgs changeEventArgs)
        {
            var test = changeEventArgs;
        }
    }

** Note i put the OnClicked and OnChanged in the .razor component @code for simplicity, eventually i will move to base class.

Upvotes: 3

Views: 3602

Answers (1)

enet
enet

Reputation: 45754

I think it should be like this:

<input @onchange="OnChanged" autoComplete="on" list="EventTypes" placeholder="Search event types..." />
<datalist id="EventTypes">
    @foreach (var eventType in EventTypes)
    {
        <option value="@eventType.Name">@eventType.Name</option>
    }
</datalist>

You can also use this form of binding on the input element: @bind="eventType.Name" instead of the change event. Note that using a change event does not result in two-way binding...

Upvotes: 3

Related Questions