我正在尝试从我的数据库中选择数据以插入到我的下拉列表中。我的问题是下拉列表什么也没显示,我也没有收到任何错误。有人可以帮忙吗?
这是我的代码:
模型:
public int id { get; set; }
public string name{ get; set; }
public IEnumerable<SelectListItem> isto { get; set; }
public ListagemEmpresas()
{
isto = GetCompanies();
}
public SelectList GetCompanies()
{
var list = new List<SelectListItem>();
string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (var con = new SqlConnection(connection))
{
con.Open();
using (var command = new SqlCommand("SELECT * FROM Companieslist", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string id = reader[0] as string;
string name = reader[1] as string;
list.Add(new SelectListItem() { Text = name, Value = id });
}
}
con.Close();
}
return new SelectList(list, "Value", "Text");
}
public class DefaultConnection : DbContext
{
public DbSet<CompanyList> abc{ get; set; }
}
控制器:
var dba = new DefaultConnection();
var query = dba.abc.Select(c => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)c.id),
Text = c.name,
});
var model = new CompanyList
{
isto = query.AsEnumerable()
};
return View(model);
看法:
@model MyProject.Models.CompanyList
@Html.DropDownListFor(m => m.name, Model.isto, "--Select One--")