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())" />
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.