Knockout - 显示javascript而不是数据绑定值

时间:2016-07-12 15:51:24

标签: javascript c# asp.net-mvc knockout.js

我创建了一个ASP.Net MVC 5项目并使用了Knockout.js库。

我有一个名为View的{​​{1}},它基本上显示了一个包含几个Statement项目的表格。

我的完整Transaction如下:

Statement.cshtml

正如您在@using Newtonsoft.Json; @model IEnumerable<ATMMVCLearning.Models.Transaction> @{ ViewBag.Title = "Statement"; } <h2>Statement</h2> <table class="table table-striped table-bordered"> <thead> <tr> <td><strong>Transaction ID</strong></td> <td><strong>Amount</strong></td> </tr> </thead> <tbody data-bind="foreach:currentTransactions"> <tr> <td data-bind="text:Id"></td> <td data-bind="text:formattedPrice"></td> </tr> </tbody> <tfoot> <tr> <td colspan="2"> <span data-bind="click:previousPage" class="glyphicon glyphicon-circle-arrow-left" style="cursor:pointer;"></span> <span data-bind="text:currentPage"></span> <span data-bind="click:nextPage"class="glyphicon glyphicon-circle-arrow-right" style="cursor:pointer;"></span> </td> </tr> </tfoot> </table> <script src="~/Scripts/knockout-3.4.0.js"></script> <script> function formattedPrice(amount) { var price = amount.toFixed(2); return price; } function StatementViewModel() { var self = this; //properties //note that there is a ko.observableArray for making bindings for array self.transactions = @Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore})); //TODO: embed transactions from server as JSON array self.pageSize = 5; //number of transactions to display per page self.currentPage = ko.observable(1); //the first observable. If the page changes, then the grid changes self.currentTransactions = ko.computed(function () { var startIndex = (self.currentPage() - 1) * self.pageSize; //because currentPage is an observable, we get the value by calling it like a function var endIndex = startIndex + self.pageSize; return self.transactions.slice(startIndex, endIndex); }); //methods to move the page forward and backward self.nextPage = function () { self.currentPage(self.currentPage() + 1); }; self.previousPage = function () { self.currentPage(self.currentPage() - 1); }; }; ko.applyBindings(new StatementViewModel()); //note this apply bindings, used extensively in KnockOut </script> 中看到的,我有两个具有数据绑定属性的<tbody>元素:

<td>

<tbody data-bind="foreach:currentTransactions"> <tr> <td data-bind="text:Id"></td> <td data-bind="text:formattedPrice"></td> </tr> </tbody> 可以参考下面的脚本部分:

formattedPrice

现在,我希望生成的View在呈现时应该显示每个页面有5个事务的表,其中每个表行显示一个Id以及它的事务量。即类似的东西:

  function formattedPrice(amount) {
    var price = amount.toFixed(2);
    return price;
  }

然而,当我渲染页面时,我得到以下结果:

enter image description here

而不是ID和金额,我得到了ID和 javascript

有什么想法吗?

更新

1 100.00 2 150.00 3 -40.00 4 111.11 5 787.33 课程如下:

Transaction

2 个答案:

答案 0 :(得分:3)

由于formattedPrice不是视图模型的一部分,因此Knockout不会自动解包它,也不会将amount参数传递给它。

请改为尝试:

<td data-bind="text: formattedPrice(Amount)"></td>

答案 1 :(得分:0)

价格可能需要计算字段,你需要绑定到价格(我认为)。我做Knockoutjs已经有一段时间了。