0

我正在尝试从我的数据库中选择数据以插入到我的下拉列表中。我的问题是下拉列表什么也没显示,我也没有收到任何错误。有人可以帮忙吗?

这是我的代码:

模型:

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--")
4

1 回答 1

2

IEnumerable<SelectListItem>在你的控制器中定义你的,如下所示。您需要先将其转换DbSet<CompanyList>为 List,然后才能使用该ToString()方法。

var query = dba.abc.ToList().Select(c => new SelectListItem
    {
        Value = c.id.ToString(),
        Text = c.name
    });

然后,在您的视图中,您将拥有(DropDownList 返回所选项目的值,而不是其文本):

@model MyProject.Models.CompanyList

@Html.DropDownListFor(m => m.id, Model.isto, "--Select One--")
于 2013-08-14T14:47:41.440 回答