简体   繁体   中英

Using ASP.NET Repeaters with Object Properties

I'm trying to use ASP.NET's Repeater objects to loop over properties of an object.

For example... I have an ObjectDataSource to grab object "Program" by ID...

Program has properties such as Program.Stakeholders and Program.Outcomes which are Lists of "Stakeholder" and "Outcome" objects.

Now... what I'd really like to do is use the Repeaters to target these Properties and loop over the lists they contain. However, as far as I know I'd have to set up a separate data source for each one, tied to an individual method to retrieve each list.

Can anyone provide a better way to use these Repeater objects, or point me at some resources which would help? If this doesn't make sense I can try to clarify it more.

Using the built-in ObjectDataSource mapping up a separate datasource for each item is probably the only straightforward way (and the only way that's easy enough to be worth the effort...).

Is it a requirement that you use the ObjectDataSource , or can you choose a different way to get the data from the storage? I would recommend either using Entity Framework (which imho rocks) or creating your own custom types to which you get the data with a custom designed DAL (which is a lot more work than using EF, but if you're, like some, concerned that EF is still in infancy this might be your option).

In either case, you'll end up with a C# class called Program , which has properties of type IEnumerable<Stakeholder> and IEnumerable<Outcome> called Stakeholders and Outcomes respectively. You can then use these as datasources for the item repeaters and set them in the ItemDataBound event of the ProgramRepeater , maybe something like this:

protected void ProgramRepeater_ItemDataBound(object sender, ItemDataBoundEvent e) {
    Program dataItem = (Program)e.DataItem;
    Repeater stakeholderRptr = (Repeater)e.Item.FindControl("ProgramRepeater");
    Repeater outecomeRptr = (Repeater)e.Item.FindControl("OutcomeRepeater");

    stakeholderRptr.DataSource = dataItem.Stakeholders;
    stakeholderRptr.DataBind();
    outecomeRptr.DataSource = dataItem.Outcomes;
    outecomeRptr.DataBind();
}

This is assuming that you're using ASP.Net WebForms, of course. In ASP.Net MVC it is even easier - you just send the Program object to the View as the Model object, and loop through its Stakeholders and Outcomes in a couple of nested for loops directly on the View .


Note: All code is provided as is, and I do not guarantee that it will run as expected or even compile. It is just to give you an idea of what to make your code do - not necessarily the exact code you need to solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM