Blazor Server设置了选择下拉列表的多个默认值
我有一个Blazor Server应用程序(.NET 6)页面,其中具有选择的下拉列表,该列表设置为允许多个选择的项目。当页面加载时,我需要设置默认值。如果我只想设置一个选定的值,则此代码正常。但是,如果我想设置多个值,它就不起作用。当我要设置多个值时,如何设置选择列表默认值?这是我所拥有的:
<select value ="@SelectedCities" @onchange="@((ev) => ListChangeEvent(ev, row_id ))" class="form-select" aria-label="Default select example" multiple rows="4">
@foreach (var i in item.values.ToList())
{
<option id="@i.Key">@i.Value</option>
}
</select>
public string[] SelectedCities { get; set; } = new[] { "New York", "Pittsburgh" };
以上代码不起作用。没有错误,它根本不会选择这两个项目。
但是,如果选择的城市不是一个数组,那么
public string SelectedCities { get; set; } = "New York";
它可以正常工作。
谢谢
I have a Blazor server app (.net 6) page that has a select drop down list, which is set to allow multiple selected items. I need to set default values, when the page loads. If I only want to set one selected value, this code works fine. But, if I want to set multiple values, it does not work. How can I set the select list default values, when there is more than one value I want to set? Here is what I have:
<select value ="@SelectedCities" @onchange="@((ev) => ListChangeEvent(ev, row_id ))" class="form-select" aria-label="Default select example" multiple rows="4">
@foreach (var i in item.values.ToList())
{
<option id="@i.Key">@i.Value</option>
}
</select>
public string[] SelectedCities { get; set; } = new[] { "New York", "Pittsburgh" };
The above code does not work. There are no errors, it simply does not select the two items.
But, if SelectedCities was not an array, like this:
public string SelectedCities { get; set; } = "New York";
It works fine.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
demo
Demo
在Blazor 6(或更高)中,您不再需要手动执行此操作。您可以直接绑定收集(尽管您仍然需要将其转换为数组)。
Enum example:
In Blazor 6 (or higher), you no longer need to manually do this. You can bind your collection directly (though you still need to convert it to an array).
Enum example:
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-6.0#multiple-option-selection-with-select-elements