如何从下拉列表中获取所选项目?

How do I get the selected item from a dropdown?

我正在编写一个 Blazor 应用,我的 Razor 文件有一个邮政编码下拉菜单。 (从 CSV 文件填充)

一些城市共享相同的邮政编码。

Zip, City
00000, CityA
00000, CityB

当我select一个城市,这里是我的代码

private void SetModel(string zipCode)
{
     var places = places.FirstOrDefault(p => p.ZipCode == zipCode);
     _model.City = place.City;
     _model.State = place.State;
     _model.ZipCode = place.ZipCode;
}

我知道 FirstOrDefault 总是会得到第一个项目,但我不知道我应该修改代码什么所以我得到用户 selected 项目

我的 Razor 文件中的代码

 <RadzenDropDown Id="locations" AllowFiltering="true" LoadData="@ChangedLocation" Data="@places" TextProperty="Key" ValueProperty="ZipCode" Change="o => SetModel(o.ToString())" />

我不确定您使用的是什么组件(RazdenDropDown?应该是 Radzen?)。但是使用 Blazor InputSelect 组件,您可以按以下方式执行此操作:

<InputSelect @bind-Value="City"> //value will be returned in City variable.
    @foreach (var item in ZipCodes)
    {
      <option value="@item.zipcode">@item.City</option>
    }
</InputSelect>

在您的代码中:

string City;
//you could intialize City as well when the component is first rendered.
var x = City; //city will contain the zipcode

请注意,在 Blazor 中从 InputSelect 获取值看似简单。该值在您的绑定变量中 returned,在本例中为 City。因此,当用户选择一个新的邮政编码时,即在变量 City 中 returned。所以当你保存数据时,你只需要使用当前在城市中的值,这就是你所需要的。

如果您使用的是 Radzen 的下拉菜单,他们的文档应该会告诉您如何获取 return 值。

首先我假设你有一个拉链模型,至少:

public class Zip
{
    public string ZipCode { get; set; }
}

使用 radzen 组件,这应该可以在你的 razor 组件标记部分实现:

<RadzenDropDown TValue="string" AllowClear="true" AllowFiltering="true" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive" Data="@_zipList" 
            TextProperty="ZipCode" ValueProperty="ZipCode" Change=@(args => OnChange(args) />

最后是组件的代码部分:

List<Zip> _zipList;
List<Place> _places;
SomeModel _model;

protected override void OnInitialized()
{
    _zipList = SomeZipService.GetAll();
    _places = SomePlaceService.GetAll();
}

private void OnChange(object args)
{
    var place = places.FirstOrDefault(p => p.ZipCode == args.ToString());
    _model.City = place.City;
    _model.State = place.State;
    _model.ZipCode = place.ZipCode;
}

或者,您可以使用 bind-Value 参数将其绑定到参数,而不将任何东西传递给 OnChange 方法。