InputSelect 中第一个选项始终为空

问题描述 投票:0回答:2

在我的 Blazor 应用程序中,

<InputSelect />
组件未按预期工作。 第一个选项显示为已选择,但当我提交表单时它始终为空。

相关型号属性:

public int? Distance { get; set; }
public Dictionary<int, string> DistanceList { get; set; }

//Set in the constructor
DistanceList = new Dictionary<int, string>()
{
    { 5, "5 Miles" },
    { 10, "10 Miles" },
    { 25, "25 Miles" }
};

选择列表:

<InputSelect @bind-Value="model.Distance">
    @foreach (var distance in model.DistanceList)
    {
        <option [email protected]>@distance.Value</option>                                                            
    }
</InputSelect>

如果我先选择“10 英里”或“25 英里”,然后选择“5 英里”,然后提交表格,距离将为 5 英里。 但如果我只是提交表格,距离为空。 尽管如此,还是选择了 5 英里。

c# asp.net-core blazor
2个回答
0
投票

可能是因为您的

Distance
尚未设置。你可以用下面的方法来做:

<InputSelect @bind-Value="model.Distance">
    @foreach (var distance in model.DistanceList)
    {
        @if (model.Distance == null)
        {
            model.Distance = @distance.Key;
        }
        <option [email protected]>@distance.Value</option>                                                            
    }
</InputSelect>

它将帮助您避免创建空选项,并允许将距离列表中的第一个值设置为所选值。


0
投票

问题是

null
不是列表中的选项,因此选择显示列表,但实际上没有选择任何内容。

Distance
设置为不可为空且具有默认有效值,或者执行如下操作:

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

<InputSelect class="form-select" @bind-Value="Distance">
    @if (Distance is null)
    {
        <option selected disabled value="null"> -- Select A Value -- </option>
    }
    @foreach (var distance in DistanceList)
    {
        <option [email protected]>@distance.Value</option>
    }
</InputSelect>

<div class="bg-dark text-white m-2 p-2">
    <pre>Distance : @Distance</pre>
</div>

@code {
    public int? Distance { get; set; }

    public Dictionary<int, string> DistanceList = new Dictionary<int, string>()
    {
        { 5, "5 Miles" },
        { 10, "10 Miles" },
        { 25, "25 Miles" }
    };
}

看起来像这样:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.