如何在 Blazor 中创建良好的自定义 DropDownList / ComboBox 项目?

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

我想在我的 Blazor-Server-App 上使用多个 ComboBox-Styled-Items。我的工作代码如下所示:

@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 value=@test.Id>@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;
        }
    }
}

问题:

1。 有没有办法通过 Class-Obj.而不是传递 Guid->string->SearchinLst -> select Obj。 例如:<option value=@test> @test.Name </option>(没有 valueStuff)

2。 如果我的代码没问题。困扰我的一件事是,我无法像在 EditForms 中那样使用占位符 =“--SelectName--”。在我的解决方案中,用户现在可以 select 选项 --SelectName--.

感谢

  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)

没有。 option元素的值属性不能是对象

  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--.

如果我理解正确,下面的方法可能会解决它(见 --SelectName-- 选项的属性)...

<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 value=@test.Id>@test.Name</option>
    }
</select>