2

So, suppose I have this web service that returns a C# List serialized to JSON, so what I get back in the client, in the viewmodel, is a JSON array:

[
    {"Id": 1, "Name": "John", "Age": 30},
    {"Id": 2, "Name": "Mike", "Age": 25},
    {"Id": 3, "Name": "Lana", "Age": 28},
]

Although this is not the actual data I'm working with, It'll be sufficient for the example.

What I'm trying to accomplish, by using knockout.js, is to data-bind each element in the above array (viewmodel) to a td tag inside a table in my view. So, in this example:

<table>
    <tr>
        <td></td> // this would represent John
        <td></td> // this would represent Mike
        <td></td> // this would represent Lana
    </tr>
</table>

Important to notice that don't want just to data-bind an element's property to a td's attribute, like

<td data-bind="text: vm.Name">

I wanted the td tag to, somehow, represent the whole person element (object).

1
  • foreach Commented Jan 12, 2014 at 23:11

2 Answers 2

2

You could also use a pre tag like this inside the each loop in the table

<pre data-bind="text: JSON.stringify(ko.toJS($data), null, 2)"></pre>

Full example would be something like this:

<table data-bind="foreach: objects">
    <tr>
        <td>
          <pre data-bind="text: JSON.stringify(ko.toJS($data), null, 2)"></pre>
        </td>
    </tr>
</table>

This will give you a pre tag with the objects JSON inside the table. I assumed that name of the value was "objects" but you can change it to whatever it needs to be.

Sign up to request clarification or add additional context in comments.

Comments

0

The actual answer to this question is in a different question, similar to this one, also made by me. Here's the link:

knockout $data binding to an HTML element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.