Blazor onchange event with select dropdown

asp.net-core blazor c#

Question

So i have been stuck trying to get a simple onchange to fire when a select dropdown value changes. Like so:

<select class="form-control d-flex" onchange="(dostuff())">
    @foreach (var template in templatestate.templates)
    {
        <option value=@template.Name>@template.Name</option>
    }
</select>

with the method being called:

void dostuff()
{
   Console.WriteLine("first spot is firing");
    _template = templatestate.templates.FirstOrDefault(x => x.Name == 
    _template.Name);
    Console.WriteLine("second spot is firing");
}

The result I get it no matter how i try to reorient it is this error in the browser.

Uncaught Error: System.ArgumentException: There is no event handler with ID 0

Is there something obvious and key that I am missing? Because I have a button onclick event that works just fine in the same page.

Accepted Answer

Your answer should be in the cshtml:

<select onchange=@DoStuff>
    @foreach (var template in templates)
    {
        <option value=@template>@template</option>
    }
</select>

Then your @functions should look like:

@functions {
    List<string> templates = new List<string>() { "Maui", "Hawaii", "Niihau", "Kauai", "Kahoolawe" };
    string selectedString = "Maui";

    void DoStuff(UIChangeEventArgs e)
    {
        selectedString = e.Value.ToString();
        Console.WriteLine("It is definitely: " + selectedString);
    }
}

You could also just use a bind...

<select bind="@selectedString"> 

but onchange=@DoStuff allows you to perform logic on selection.


Popular Answer

For starters you are not using the correct bind syntax:

onchange="@dostuff"

notice the @




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why