从外部脚本调用knockout.js函数

时间:2014-04-30 19:35:25

标签: jquery asp.net-mvc knockout.js

好的,我不习惯使用淘汰赛了,我想知道这是怎么回事。

我将它与ASP.NET MVC结合使用,如果这有任何区别的话。

理想情况下,我想在外部脚本文件中执行所有功能。在脚本文件中,我有以下功能:

function GetIncidentNotes (incidentID, node) {
    $.getJSON('GetIncidentNotes', { IncidentID: incidentID }, function (data, status, xhr) {
        var notesViewModel =
            { notesArray: ko.observableArray(data) }
        ko.applyBindings(notesViewModel, document.getElementById(node));
    });

在我的cshtml razor文件中,我使用以下内联脚本和相关的html进行测试:

<script type="text/javascript">
    $(document).ready(function () {
        $("#getNotes").on('click', function () {
            var id = 124;
            GetIncidentNotes(id, 'incidentNotes');
        });
    });
</script>

<table id="incidentNotes" data-bind="visible: notesArray().length > 0">
    <tbody data-bind="foreach: notesArray">
       <tr>
           <td><span data-bind="text: object.NoteID"></span></td>
       </tr>
    </tbody>
</table>

我正在获取JSON数组,但之后没有任何内容填充我的表。我肯定做错了什么,但我不确定是什么。

这是一个被带回的数组的例子:

[{"NoteID":3,
"IncidentID":124,
"GrievanceID":null,
"NoteSubtypeID":null,
"NoteDate":"2013-06-13T14:25:42.95",
"NoteBody":"travissimantor non non habitatio dolorum Quad esset rarendum eggredior. quartu et transit. imaginator Versus bono",
"CreateDate":"2014-04-23T16:12:01.553",
"CreateUser":"jsteranko",
"UpdateDate":"2014-04-23T16:12:01.553","UpdateUser":"jsteranko"},

{"NoteID":1,
"IncidentID":124,
"GrievanceID":496,
"NoteSubtypeID":6,
"NoteDate":"2000-01-30T13:27:14.51",
"NoteBody":"linguens e dolorum non transit. Quad imaginator Pro homo, quartu Quad Longam, rarendum Sed si egreddior estum. quartu",
"CreateDate":"2014-04-23T16:12:01.553",
"CreateUser":"jsteranko",
"UpdateDate":"2014-04-23T16:12:01.553",
"UpdateUser":"jsteranko"}]

3 个答案:

答案 0 :(得分:0)

这里有一个数组,所以没有要显示的文字......你应该将你的html转换成什么样的

<!-- ko foreach: notesArray -->
<span data-bind="text: propertyOfNote"></span>
<!-- /ko -->

答案 1 :(得分:0)

此时看起来您需要一个断点来检查值。如果您完全确定您的JSON正确返回,那么这将是我的下一步。

ko.applyBindings(notesViewModel, document.getElementById(node));

变量notesViewModel和节点是你期望的吗?

答案 2 :(得分:0)

原来这确实是一个映射问题。我下载映射插件和瞧。工作js功能:

function GetIncidentNotes(incidentID, node) {
    $.getJSON('GetIncidentNotes', { IncidentID: incidentID }, function (data, status, xhr) {
        var notesViewModel = { notesArray: [] };
        notesViewModel.notesArray = ko.mapping.fromJS(data);
        ko.applyBindings(notesViewModel, document.getElementById(node));
    });
}