Search code examples
c#htmlrazorblazor

Blazor detect change on select element inside a foreach loop


I have a root object with a property named Exercises, which is a List. In my HTML I loop over this list as below:

@foreach(WorkoutExerciseDto workoutExerciseDto in Workout.Exercises){
    <select class="form-select" @bind="workoutExerciseDto.ExerciseId">
        <option value="1">Exercise 1</option>
        <option value="2">Exercise 2</option>
        <option value="3">Exercise 3</option>
    </select>
}

In my code section I have this method:

public void GetChangedObject(WorkoutExerciseDto workoutExerciseDto){
    // When a value has been selected I want the WorkoutExerciseDto object in that foreach loop. 
}

So, when a new value has been selected I want that changed object in the GetChangedObject method. How do I do this? I can't set the onchange attribute because I already used the bind attribute. I could wing this, but I would like to know the best method to approach my problem. Thanks in advance


Solution

  • You can use the @onchange directive alongside another directive like @oninput, just need to specify that the first @bind is for the oninput event.

    @foreach(WorkoutExerciseDto workoutExerciseDto in Workout.Exercises){
        <select class="form-select" 
        @bind="workoutExerciseDto.ExerciseId" @bind:event="oninput"
        @onchange="() => GetChangedObject(workoutExerciseDto)">
            <option value="1">Exercise 1</option>
            <option value="2">Exercise 2</option>
            <option value="3">Exercise 3</option>
        </select>
    }
    

    Snippet demo