Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

c# - Populating a dropdown list from a database with selected items then the rest in alphabetical order

I have a telephone prefix code dropdown select box, which is populated from a database. I currently have an alphabetical dropdown list containing the country names & dial codes eg. UK (+44), etc.

Ideally I would like to place the top 4 most popular countries (UK, US, France, Spain) at the top of the list (with the full list following them), however I'm unsure how & where to filter this list. Potentially using an optgroup tag and using ngFor to loop through the countries.

component.html

<select
                class="block appearance-none text-gray-600 w-full"
                [(ngModel)]="value.code" name="code" (change)="modelChange($event)">
                    <option *ngFor="let country of countries" [value]="country.phoneCode">
                        {{ country.name + ' (+' + country.phoneCode + ')'}}
                    </option>

</select>

service.cs

public IList<CountryViewModel> GetCountries()
        {
            using (var db = new ApplicationDbContext())
            {
                var countries = db.Countries.OrderBy(x => x.Name).ToList();
                return mapper.Map<List<Country>, List<CountryViewModel>>(countries);
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In TypeScript you can do something like this to sort it

Countries.sort((a, b)=> +['UK', 'US', 'France', 'Spain'].includes(b.name))

However be aware that sort does not mutate the existing array, it just returns a new sorted array, which you can then use in your html to bind to the select box


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...