Question

I'm looking at example of using hadlebars.js, where template processing looks like:

 var source   = $("#some-template").html();
 var template = Handlebars.compile(source);
 var data = { users: [
  {username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
  {username: "allison", firstName: "Allison", lastName: "House", email: "allison@test.com" },
  {username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" }
]};
$("#content-placeholder").html(template(data));

and template is:

  <tbody>
  {{#users}}
    <tr>
      <td>{{username}}</td>
      <td>{{firstName}} {{lastName}}</td>
      <td>{{email}}</td>
    </tr>
  {{/users}}
</tbody>

Now I have JSON result from ASP.NET MVC and I can't think the way I should descripbe my template, because it does not have "users" property, it looks like:

{[{username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" }]}

Can I somehow affect JsonResult to output what I need, or there is a way to fix template without touching the controller code?

Was it helpful?

Solution

In your controller replace:

return Json(users);

with:

return Json(new { users = users });

OTHER TIPS

Alternatively, without introducing the anonymous object with the users property, you can change your template like so:

<tbody>
  {{#each this}}
    <tr>
      <td>{{username}}</td>
      <td>{{firstName}} {{lastName}}</td>
      <td>{{email}}</td>
    </tr>
  {{/each}}
</tbody>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top