ASP.NET MVC JsonResult和把手,没有抓地力?

时间:2012-01-23 13:58:28

标签: asp.net-mvc json asp.net-mvc-3 handlebars.js

我正在查看使用hadlebars.js的示例,其中模板处理如下:

 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));

和模板是:

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

现在我有来自ASP.NET MVC的JSON结果,我想不出我应该描述我的模板的方式,因为它没有“users”属性,它看起来像:

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

我可以以某种方式影响JsonResult输出我需要的东西,还是有办法修复模板而不触及控制器代码?

2 个答案:

答案 0 :(得分:8)

在您的控制器中替换:

return Json(users);

使用:

return Json(new { users = users });

答案 1 :(得分:7)

或者,如果不引入具有users属性的匿名对象,您可以像这样更改模板:

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