Search code examples
comboboxblazor

How to create a good custom DropDownList / ComboBox item in Blazor?


I want to use multiple ComboBox-Styled-Items on my Blazor-Server-App. My working code for this looks like this:

@page "/dropdownlist"
<h3>DropDownList - ComboBox</h3>

<select class="form-control col-6" @onchange="@(x => OnSelChange(x.Value.ToString()))">
    <option value="">--SelectName--</option>
    @foreach (var test in TestModelsLst)
    {
        <option [email protected]>@test.Name</option>
    }
</select>

@if (SelectedTestModel != null)
{
    <p>Sel TestModel-Obj.Name: @SelectedTestModel.Name</p>
}

@code {
    public TestModel SelectedTestModel;

    public void OnSelChange(string guidAsString)
    {
        SelectedTestModel = TestModelsLst.FirstOrDefault(x => x.Id.ToString() == guidAsString);
    }

    //---------------

    public List<TestModel> TestModelsLst = new List<TestModel>
    {
        new TestModel("Jonny"),
        new TestModel("Sarah"),
        new TestModel("Tom")
    };

    public class TestModel
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public TestModel(string name)
        {
            Id = Guid.NewGuid();
            Name = name;
        }
    }
}

Questions:

1. Is there a way to pass the Class-Obj. instead of passing Guid->string->SearchinLst -> select Obj. e.g.: <option value=@test> @test.Name </option> (without the valueStuff)

2. If my code is okay. The one thing that bothers me, is that I can't figur out to use a placeholder="--SelectName--" as I did in EditForms. In my solution right now user can select the option --SelectName--.

Thx


Solution

    1. Is there a way to pass the Class-Obj. instead of passing Guid->string->SearchinLst -> select Obj. e.g.: @test.Name (without the valueStuff)

    Nope. The value property of the option element cannot be an object.

    1. If my code is okay. The one thing that bothers me, is that I can't figur out to use a placeholder="--SelectName--" as I did in EditForms. In my solution right now user can select the option --SelectName--.

    If I understand correctly, the following might solve it (see attributes of --SelectName-- option) ...

    <select class="form-control col-6" @onchange="@(x => OnSelChange(x.Value.ToString()))">
        <option value="" disabled selected hidden>--SelectName--</option>
        @foreach (var test in TestModelsLst)
        {
            <option [email protected]>@test.Name</option>
        }
    </select>