Search code examples
asp.netlistrazordrop-down-menu

C# asp.net dynamically populate <select> list


.net 5.0 c# Razor

I have been trying for a few days to dynamically populate a <select> list with 164 country names that sit in a DB column. I have worked through various sources online and 'nearly' have it working, but I'm stuck at the final hurdle.

DB Countries Column

The list populates one name at a time, overwriting the previous one each time. Only the final value from the DB column displays in the view.

Dropdown List

HTML

            <div class="form-group">
                <label asp-for="Input.Country" class="font-heading" id="CountryHeading">@_loc[Model.CountryHeading]</label>
                <div class="input-group">
                    <label asp-for="Input.Country" class="input-group-text" for="inputGroupCountrySelect">Country</label>
                    <select asp-for="Input.Country" class="form-control" asp-items="@Model.CountryList" id="inputGroupCountrySelect">
                    </select>
                    <br />
                </div>
            </div>

Controller

    public IEnumerable<SelectListItem> CountryList { get; set; }

    public class InputModel
    {
        [ExStringLength(100, MinimumLength = 1)]
        [DataType(DataType.Text)]
        [Display(Name = "Country")]
        public string Country { get; set; }
    }

    public async Task<IActionResult> OnGetAsync(string email)
    {
        List<string> countriesList = GetCountriesList.GetCountries();
        Debug.WriteLine("************** countriesListReturned: " + countriesList.ToString());
        for (int i = 0; i < 195; i++)
        {
            try
            {
                Debug.WriteLine("************** i Returned: " + i.ToString());
                Debug.WriteLine("************** countriesList[i]: " + countriesList[i]);

                CountryList = new SelectListItem[]
                {
                new SelectListItem(countriesList[i], countriesList[i])
                };
            }
            catch
            {
                Debug.WriteLine("************** break");
                break;
            }
        }

        [normal other code to populate the view goes here]

        return Page();
    }

GetCountriesList.cs - to retrieve list from DB

Note: I'm planning to change the DB usage anyway because it takes 19 seconds to loop through the table and retrieve the values, which is way too long. But I still need to know why its not working.

using MyApp.Data;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace MyApp.Areas.FunctionalLogic
{
    public class GetCountriesList
    {
        private static readonly ApplicationDbContext _context = new();

        public static List<string> GetCountries()
        {
            _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            var Countries = _context.Countries.FirstOrDefault();
            //Debug.WriteLine("************** Countries: " + Countries);

            List<string> countriesList = new();

            if (Countries != null)
            {
                for (int i = 0; i < 195; i++)
                {
                    countriesList = _context.Countries.Where(c => c.Country != null).Select(c => c.Country).ToList();

                    Debug.WriteLine("************** countriesList a: " + countriesList[i]);
                    Debug.WriteLine("************** countriesList b: " + countriesList);
                    Debug.WriteLine("************** countriesList c: " + i);
                }

            }
            return countriesList;
        }
    }
}

Any ideas why I'm just getting the last DB value in my dropdown list?


Solution

  • just do this

    public  List<SelectListItem> GetCountries()
     {
    return _context.Countries.Select(i=> new SelectListItem{
                                              Value=i.Id.ToString,
                                              Text=i.Name
                                        } ).ToList();
    }
    

    use it

     CountryList=GetCountries();