ASP.NET MVC JsonResult 和车把,没有握力?

发布于 2024-12-28 06:40:04 字数 1478 浏览 2 评论 0原文

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

 var source   = $("#some-template").html();
 var template = Handlebars.compile(source);
 var data = { users: [
  {username: "alan", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
  {username: "allison", firstName: "Allison", lastName: "House", email: "[email protected]" },
  {username: "ryan", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]};
$("#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: "[email protected]" }]}

我可以以某种方式影响 JsonResult 输出我需要的内容,或者有一种方法可以在不接触控制器代码的情况下修复模板?

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: "[email protected]" },
  {username: "allison", firstName: "Allison", lastName: "House", email: "[email protected]" },
  {username: "ryan", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]};
$("#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: "[email protected]" }]}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梨涡 2025-01-04 06:40:04

在您的控制器中将: 替换

return Json(users);

为:

return Json(new { users = users });

In your controller replace:

return Json(users);

with:

return Json(new { users = users });
风吹雨成花 2025-01-04 06:40:04

或者,在不引入带有 users 属性的匿名对象的情况下,您可以像这样更改模板:

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文