c# - 在 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 是空的。任何人都可以帮忙吗?
解决方案
基本上要绑定我们使用以下代码的下拉列表,试试这个。
DropDownList1.DataSource = GetCompanies();
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
推荐阅读
- regex - 正则表达式 - 如何忽略以逗号结尾的数字
- c# - 由于我不能在 C# 中使用带有隐式变量的 lambda 函数,我可以在这里替换什么?
- soap - METRO SOAP Web 服务不适用于 Tomcat 9 和 Java 11
- postgresql - 在 postgresql 中使用替换更新语句
- validation - 关于表单验证
- amazon-web-services - Snowflake:数据从 AWS 美国拆分到 AWS 澳大利亚
- rest - 如何创建正确的 API URL 来获取数据
- python - 如何在python中格式化数字?
- python - PyLint:模块“main_app”中没有名称“新文件”
- mysql - Spring Boot JPA:如何将字段映射到数据类型不固定的列