Markus_DE_HH
Markus_DE_HH

Reputation: 1071

GroupBy Knockout.js

I have this Razor code in C# and try to do the same in Knockout

 @foreach (var group in Model.Details.SonstigeNummern.OeReferenznummern.GroupBy(x => x.Hersteller))
                {
                    <tr class="ListItem @oddeven">
                        <td>@group.Key</td>
                        <td>
                            @foreach (var nummer in group)
                            { 
                                @nummer.Nummer<br />
                            }
                        </td>
                    </tr>
                }

I have no clue how i could manage the GroupBy.

My Viewmodel has the same Syntax as my c# model

Can Someone help with this?

Sincerly

Upvotes: 0

Views: 941

Answers (1)

Damien
Damien

Reputation: 8987

I am not sure about the linq query. But I think you should do something like this. As you can see I just convert all data into arrays and then into JSON string. And on this client side I re-convert them into javascript Object.

<table data-bind="foreach: groups">
     <tr class="ListItem @oddeven" >
        <td data-bind="value: Key"></td>
        <td data-bind="foreach: Nummers">
            <span data-bind="text: $data"></span>
        </td>
    </tr>
 </table>



<script type="text/javascript">
    var data= JSON.parse('@Html.Raw(Json.Encode(Model.Details.SonstigeNummern.OeReferenznummern.GroupBy(x => x.Hersteller).Select( g => new {Key = g.Key, Nummers =  g.ToArray()}).ToArray()))');
    var vm = { groups: data};
    ko.applyBindings(vm);
</script>

I hope it helps.

Upvotes: 2

Related Questions