I'm trying to select data from my database to insert into my dropdown list. My problem is that the dropdown list shows nothing and I don't receive any errors. Can someone give a hand with this please?
Here is my code:
Model:
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; }
}
Controller:
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);
View:
@model MyProject.Models.CompanyList
@Html.DropDownListFor(m => m.name, Model.isto, "--Select One--")
isto, but notNameCompanyListdoes not have a `nome_empresa' property that you are using.CompanyListnotSelectListItem