我的数据源是webforms项目中的客户列表
protected void Page_Load(object sender, EventArgs e)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { FirstName = "John", PhoneNumber = "999.999.9999" });
customers.Add(new Customer() { FirstName = "Jane", PhoneNumber = "999.999.9999" });
}
有没有办法在Web表单项目的aspx页面中迭代它。 (这在使用该模型的mvc中很容易)?
答案 0 :(得分:0)
使用Repeater控件。这是一个例子:
标记:
<asp:Repeater ID="CustomerRepeater" runat="server">
<ItemTemplate>
<span>Name:</span> <%# Eval("FirstName") %>
<span>Phone:</span> <%# Eval("PhoneNumber ") %>
</ItemTemplate>
</asp:Repeater>
代码背后:
protected void Page_Load(object sender, EventArgs e)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { FirstName = "John", PhoneNumber = "999.999.9999" });
customers.Add(new Customer() { FirstName = "Jane", PhoneNumber = "999.999.9999" });
CustomerRepeater.DataSource = customers;
CustomerRepeater.DataBind();
}
答案 1 :(得分:0)
使用服务器控件的“DataSource”:(在示例DropDownList中)
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.ddlCustomers.DataSource = this.GetCustomers();
this.ddlCustomers.DataBind();
}
}
public List<Customer> GetCustomers()
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { FirstName = "John", PhoneNumber = "999.999.9999" });
customers.Add(new Customer() { FirstName = "Jane", PhoneNumber = "999.999.9999" });
return customers;
}
Default.aspx的
<asp:DropDownList ID="ddlCustomers" runat="server" DataTextField="FirstName" DataValueField="FirstName"></asp:DropDownList>
或者,如果您需要,可以在aspx中使用'MVC-style':
<% foreach(WebApplication1.Customer customer in this.GetCustomers()) { %>
<span><%= customer.FirstName %></span>
<% } %>