噜噜哒
开拓者方式:要做到这一点,他们打算在 Blazor 中完成,首先使用 Blazor 组件。下面的示例使用组件 SingleSelect.razor,它是一个简化的 HTML Select 元素。该组件由 VisualStudio 根据 razor 组件文件的名称自动生成的标签引用,因此在这种情况下标签将为<SingleSelect>.为了从子组件获取值,父组件创建了一个指向子组件的引用变量。这是通过在父级中创建子级的局部变量来完成的:private SingleSelect singleSelect;然后将其链接到子标签中:<SingleSelect @ref="singleSelect" Options="SingleSelectOptions"></SingleSelect>这允许通过使用引用变量来引用子数据:singleSelect.SelectedOption.Value以下几页给出了一个完整的例子。Index.razor page@page "/"<h3>Single Select Example</h3><h5 class="mt-2">Make your selection</h5><SingleSelect @ref="singleSelect" Options="SingleSelectOptions"></SingleSelect><button class="btn btn-primary mt-2" @onclick="SubmitSingleSelect">Submit</button><h5 class="mt-2">The following was selected:</h5><p>@singleSelectResult</p>@code{ public partial class Index { SingleSelect singleSelect; string singleSelectResult; List<SingleSelectOption> SingleSelectOptions = new List<SingleSelectOption> { new SingleSelectOption{ Id=1, Value="One"}, new SingleSelectOption{ Id=2, Value="Two"}, new SingleSelectOption{ Id=3, Value="Three"}, new SingleSelectOption{ Id=4, Value="Four"}, new SingleSelectOption{ Id=5, Value="Five"}, new SingleSelectOption{ Id=6, Value="Six"}, new SingleSelectOption{ Id=7, Value="Seven"}, new SingleSelectOption{ Id=8, Value="Eight"}, new SingleSelectOption{ Id=9, Value="Nine"}, new SingleSelectOption{ Id=10, Value="Ten"}, new SingleSelectOption{ Id=11, Value="Eleven"}, }; private void SubmitSingleSelect() { singleSelectResult = singleSelect.SelectedOption.Value; } }}SingleSelect.razor page<div class="container"> <div class="row"> <div class="col-3"> <select id="NotSelected" class="border" multiple="multiple" size="@boxSize" style="width: 200px"> @foreach (var option in Options) { <option id="@option.Id" @onclick="@(() => Select(option))">@option.Value</option> } </select> </div> </div></div>@code { [Parameter] public List<SingleSelectOption> Options { get; set; } = new List<SingleSelectOption>(); public SingleSelectOption SelectedOption { get; set; } = new SingleSelectOption { Id = 0, Value = " "}; private int boxSize = 5; private void Select(SingleSelectOption option) { SelectedOption = option; } public class SingleSelectOption { public int Id { get; set; } public string Value { get; set; } }}