BLAZOR WAY:
要以 Blazor 的方式完成此操作,首先使用 Blazor 组件。下面的示例使用 SingleSelect.razor 组件,该组件是一个简化的 HTML Select 元素。
该组件通过标签引用,该标签由 Visual Studio 根据 Razor 组件文件的名称自动生成,因此在本例中,标签将为 <SingleSelect>
。
为了从子组件获取值,父组件创建指向子组件的引用变量。
这是通过在父组件中创建子组件的局部变量来完成的:
private SingleSelect singleSelect;
然后在子标记中进行链接:
<SingleSelect @ref="singleSelect" Options="SingleSelectOptions"></SingleSelect>
这允许通过利用参考变量引用子数据:
singleSelect.SelectedOption.Value
以下页面提供了一个完整的示例。
Index.razor 页面
@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; }
}
}
ref
访问值就简单得多了,我不明白有什么意义。 - smj