开发者

list<type> access in webform markup

my datasource is a list of c开发者_如何学编程ustomers in a webforms project

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" });

}

is there a way to iterate that in an aspx page of a web forms project. (this is easy in mvc using the model)?


Use the Repeater control for this. Here is an example:

Markup:

<asp:Repeater ID="CustomerRepeater" runat="server">
    <ItemTemplate>
        <span>Name:</span> <%# Eval("FirstName") %>
        <span>Phone:</span> <%# Eval("PhoneNumber ") %>
    </ItemTemplate>
</asp:Repeater>

Code behind:

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();
}


Use `DataSource' of server control: (in example 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>

Or if you needed you can use 'MVC-style' in aspx:

<% foreach(WebApplication1.Customer customer in this.GetCustomers()) { %>
    <span><%= customer.FirstName %></span>
<% } %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜