Search code examples
c#asp.net-corerazorblazorblazor-server-side

How to trigger a method with parameter through a dropdown in Blazor?


I would like to trigger a method through a dropdown list in my editform. The method should be fired when i change the value in my dropdownlist. But it seems not to work, anyone know what i doing wrong?

My code in UI.


<EditForm Model="@exampleModel">
   <p>
        <label>
            Name:
            <InputSelect @onchange="() => GetNames(name)" @bind-Value="name">
                @foreach (string item in names)
                {
                    <option value="name">@item</option>
                }
            </InputSelect>
        </label>
    </p>
<EditForm />

My code

@code {

public string? name{ get; set; }

  public async Task GetNames(string name)
 {
   // Get Names
 }

    string[] names = new string[] { "test", "test1", "test2", "test3", "test4" };



}


Solution

  • Try:

    <EditForm Model="@exampleModel" >
    
       <p>
            <label>
                Name:
                <Select @onchange="GetNames" >
                    @foreach (var item in names)
                    {
                        <option value="@item">@item</option>
                    }
                </Select>
            </label>
        </p>
    </EditForm>
    @code {
            private ExampleModel exampleModel = new();
            public string? name { get; set; }
    
            
        public async Task GetNames(ChangeEventArgs e)
        {
            // Get Names
            name = e.Value.ToString();
        }
            string[] names = new string[] { "test", "test1", "test2", "test3", "test4" };
    
    
    
        }
    

    result:

    enter image description here