正在将数据库绑定到下拉列表

本文关键字:下拉列表 绑定 数据库 | 更新日期: 2023-09-27 18:24:00

我是MVC的新手,仍在学习我的方法,我正在尝试填写一个下拉列表。我有以下代码(型号):

public class SchoolCodes
{
    public int escuelaCode { get; set; }
    public string escuelaName { get; set; }
}
public class AllSchoolCodes
{
    public List<SchoolCodes> GetSchools()
    {
        List<SchoolCodes> Codes = new List<SchoolCodes>();
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MCE"].ConnectionString);
        SqlCommand comm = new SqlCommand("SELECT EscuelaCode, EscuelaName from Escuelas", conn);
        conn.Open();
        using (var dataReader = comm.ExecuteReader())
        {
            while (dataReader.Read())
            {
                SchoolCodes ur = new SchoolCodes();
                ur.escuelaCode = Convert.ToInt32(dataReader["EscuelaCode"]);
                ur.escuelaName = Convert.ToString(dataReader["EscuelaName"]);
                Codes.Add(ur);
            }
        }
        return Codes;

    }
}
public class GetSchoolCodeViewModel
{
    [Display(Name = "Escuela: ")]
    public int SelectedEscuelaCode { get; set; }
    public IEnumerable<SelectListItem> AllSchoolCodes { get; set; }
}

控制器:

private IEnumerable<SelectListItem> GetCode()
    {
        var dbSchoolCodes = new AllSchoolCodes();
        var code = dbSchoolCodes
                    .GetSchools()
                    .Select(x =>
                            new SelectListItem
                            {
                                Value = x.escuelaCode.ToString(),
                                Text = x.escuelaName
                            });
        return new SelectList(code, "Value", "Text");
    }

public ActionResult Index()
    {
        var model = new GetSchoolCodeViewModel
        {
        AllSchoolCodes = GetCode()
        };
        return View(model);
     //   return View();
    }

现在,我在索引控制器中收到以下错误:错误1无法将类型"System.Collections.Generic.IEnumerable"隐式转换为"System.Collections.Generic.IEnumerable"。存在显式转换(是否缺少强制转换?)。我被困在这里,完全不知道该怎么办。任何帮助都会很棒。

正在将数据库绑定到下拉列表

Ypu不需要再次创建SelectList,因为您正在重新使用IEnumerable<SelectListItem>,您只需通过以下方式返回SelectList

private SelectList GetCode()
{
        var dbSchoolCodes = new AllSchoolCodes();
        var code = dbSchoolCodes.GetSchools();

        return new SelectList(code, "escuelaCode", "escuelaName");
}

或者如果你想返回IEnumerable<SelectListItem>,那么你可以这样做,不需要再次创建SelectList

private IEnumerable<SelectListItem> GetCode()
    {
        var dbSchoolCodes = new AllSchoolCodes();
        var code = dbSchoolCodes
                    .GetSchools()
                    .Select(x =>
                            new SelectListItem
                            {
                                Value = x.escuelaCode.ToString(),
                                Text = x.escuelaName
                            });
        return code;
    }