首页 > 解决方案 > 在 html 中将 DataSource 设置为 ASP.NET DropDownList 不起作用

问题描述

我尝试按照以下代码(在 .aspx 文件中)设置 DropDownlist 的 DataSource:

<tr>
    <td class="Col1">
        <asp:Label ID="lbCompany" runat="server" Text="Thuộc công ty:"></asp:Label>
    </td>
    <td class="Col2">
        <asp:DropDownList CssClass="form-control" ID="ddlCompany" DataSource="<%# GetCompanies() %>" DataValueField="Id" DataTextField="Name" runat="server"></asp:DropDownList>
    </td>
    <td class="Col3">
        <asp:Label ID="lbCompanyError" runat="server" Text=" "></asp:Label>
    </td>
</tr>

在后面的 C# 代码中,在 aspx.cs 文件中,我声明了 GetCompanies() 方法,如下所示:

protected IEnumerable<Company> GetCompanies()
{
    using (var bkDb = new BrickKilnDb())
    {
        return bkDb.Companies.ToList();
    }
}

但在运行时,DropDownList 是空的。任何人都可以帮忙吗?

标签: c#asp.net

解决方案


基本上要绑定我们使用以下代码的下拉列表,试试这个。

DropDownList1.DataSource = GetCompanies();
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();

推荐阅读