How do I get the selected item from a dropdown?

Viewed 2968

I am writing a Blazor app and my Razor file has a dropdown for Zip Codes. (populated from a CSV file)

Some cities share the same zip code.

Zip, City
00000, CityA
00000, CityB

When I select a city, here is my code

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;
}

I know FirstOrDefault will always get the first item but I don't know what I should modify the code so I get the User selected item

The code in my Razor file

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

First I assume you have a model for your zips, at least:

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

Using Radzen components this should do the trick in your razor component markup part:

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

And finally the code part of your component:

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;
}

Alternatively you can use the bind-Value parameter to bind it to a parameter and not pass anything to the OnChange method.

I am not sure what component you are using (RazdenDropDown? Should be Radzen?). But using the Blazor InputSelect component, you would do it in the following manner:

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

And in your code:

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

Note that getting value from InputSelect in Blazor is deceptively simple. The value is returned in your bound variable, in this case it is City. So when the user selects a new zipcode, that is returned in the variable City. So when you are saving data, you just use the value that is currently in City, and that is what you need.

If you are using a dropdown from Radzen, their documentation should show you how to get the return value.

Related