I'm trying to figure out how to iterate through a .Net grouping using the knockout foreach data-bind. The issue I have is that I don't know how to iterate over a .Net collection of IGroupings once it's been serialized to JSON...
On the server side I have a .Net object that looks like this:
public class BookingResult
{
public IEnumerable<IGrouping<DateTime, BookingLeg>> Grouped { get; set; }
}
public class BookingLeg
{
public string DepartureDate { get; set; }
public string ArrivalDate { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
And I'm creating the Grouped
property by grouping a collection of BookingLeg
entities by their StartDate
. I then return the BookingResult
entity using JSON. The JSON that is generated for the Grouped
property looks like this (I've collapsed and expanded the nodes to give you a better overview of what was generated):
What I'd like to do on my client is create a template and bind to the knockout foreach binding outputting the key as a list header and then for every value in that key, output some details from the value. It would look something like this:
01/01/2012
- Transfer
- Flight
- Transfer
03/01/2012
- Transfer
- Cruise
...
I've attempted to do this like so:
<ul data-role="listview" data-bind="foreach: Grouped">
<li data-role="list-divider"><span data-bind="text: Key"></span></li>
<li data-bind="text: Name, click: $parent.getBookingLegDetail"></li>
</ul>
I know the above is wrong, for one - Key doesn't exist in Grouped.
Does anyone know how I can create a template to correctly output the Key and Values of my grouping in a list? BTW I'm also using jquery mobile here (hence the data-role stuff).
Thanks!
James
The JavaScriptSerializer doesn't handle the Key property in IGrouping objects. See this question for a similar problem and possible solutions.