C# asp.net 动态填充 <select> 列表

C# asp.net dynamically populate <select> list

.net 5.0 C# 剃须刀

几天来,我一直在尝试动态填充一个 <select> 列表,其中包含位于数据库列中的 164 个国家/地区名称。我已经通过各种在线资源进行了研究,'nearly' 可以正常工作,但我遇到了最后的障碍。

该列表一次填充一个名称,每次都覆盖前一个。视图中仅显示数据库列的最终值。

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>

控制器

    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 - 从数据库中检索列表

注意:我打算改变数据库的使用,因为它需要 19 秒来遍历 table 并检索值,这太过分了长。但我仍然需要知道为什么它不起作用。

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

知道为什么我只得到下拉列表中的最后一个 DB 值吗?

问题是:

CountryList = new SelectListItem[]
   {
       new SelectListItem(countriesList[i], countriesList[i])
   };

每次您创建一个包含一个元素的新项目列表时。您应该将所有项目添加到一个列表中。类似的东西:

public async Task<IActionResult> OnGetAsync(string email)
{
    List<string> countriesList = GetCountriesList.GetCountries();
    Debug.WriteLine("************** countriesListReturned: " + countriesList.ToString());

    CountryList = countriesList.Select(x => new SelectListItem(x, x));

    [normal other code to populate the view goes here]

    return Page();
}

就这样做

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

使用它

 CountryList=GetCountries();