Home > Back-end >  How to handle order change in an ordered <select> element
How to handle order change in an ordered <select> element

Time:02-15

Suppose I have the following code to produce a drop down element and a text input to change the name of an item in a sorted list:

@page "/"

<input @bind="@SelectedFoo.Name"/>

<select @bind="SelectedFooId">
    @foreach (var foo in MyFoos.OrderBy(e => e.Name))
    {
        <option value="@foo.Id">@foo.Name</option>
    }
</select>

@code
{
    private Foo SelectedFoo { get; set; }
    private string _selectedFooId;

    private string SelectedFooId
    {
        get => _selectedFooId;
        set
        {
            _selectedFooId = value;
            SelectedFoo = MyFoos.Find(e => e.Id == _selectedFooId);
        }
    }

    private List<Foo> MyFoos { get; } = new()
    {
        new Foo { Name = "A Foo", Id = "0" },
        new Foo { Name = "B Foo", Id = "1" },
        new Foo { Name = "C Foo", Id = "2" }
    };

    protected override void OnInitialized()
    {
        SelectedFooId = MyFoos.First().Id;
    }


    public class Foo
    {
        public string Name { get; set; }
        public string Id { get; set; }
    }
}

enter image description here

If I now select "C Foo" and change its name to "Ab Foo" it is now correctly ordered in the drop down above "B Foo", but the select element now displays "B Foo" instead of the "Ab Foo" as selected.

enter image description here

enter image description here

How do I update the select element's selected item to reflect the change in order?

  • Framework: .NET 6.0
  • Browser: Any

CodePudding user response:

Try to use the @key directive like this:

<option @key="foo" value="@foo.Id">@foo.Name</option>
  • Related