获取 MVC Knockout 中可变长度列表中项目的总和

Get the sum of on item in a variable length list in MVC Knockout

我使用knockout和ajax post上传文件到服务器,返回文件信息然后显示在table。

我用了 Steven Sanderson's Example 来做这件事。

这很好用。

但是,我想得到所有文件大小的总和。我试过这个:

    self.Upload = function () {
            var formData = new FormData();
            var file = document.getElementById("fileupload").files[0];
            formData.append("FileUpload", file);
            var action = "Upload";

            $.ajax({
                type: "POST",
                url: options.url + action,
                data: formData,
                contentType: false,
                processData: false,
                success: function (result) {
                    self.AddDoc(result);
                }
            });
        }

        self.AddDoc = function (data) {
            self.Model.CurrentStep().Files.push({ ID: data.ID, Name: data.Name, Extension: data.Extension, ContentType: data.ContentType, Size: data.Size, RawSize: data.RawSize, Content: data.Content, FilePath: data.FilePath, Folder: data.Folder });
        }

        self.TotalSize = ko.computed(function () {
            var total = 0;

            if (self.Model.CurrentStep() === 5) {
                ko.utils.arrayFilter(self.Model.CurrentStep().Files(), function (item) {
                    total += item.RawSize;
                });
            }

            return total
        });

 <table id="FileList" class="table table-responsive table-striped">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayName("Document Name")
                    </th>
                    <th style="width: 150px;">
                        @Html.DisplayName("Document Size (MB)")
                    </th>
                    <th style="width: 40px;">
                        @Html.DisplayName("View")
                    </th>
                    <th style="width: 40px;">
                        @Html.DisplayName("Delete")
                    </th>
                </tr>
            </thead>
            <tbody data-bind="template: { name: 'FileRowTemplate', foreach: Model.Step5.Files }"></tbody>
            <tfoot>
                <tr>
                    <td colspan="4">
                        @Html.DisplayNameFor(model => model.Size)
                        <span data-bind="text: TotalSize" />
                    </td>
                </tr>
            </tfoot>
        </table>

self.TotalSize 始终为 0。

请问我该如何解决这个问题?

解法:

根据 Chris Pratt 的建议,我将其更改为:

   if (self.Model.CurrentStep() === 5) 

到 如果(self.Model.CurrentStep()。文件)

问题解决了。

问题似乎出在这里:

if (self.Model.CurrentStep() === 5) {
    ko.utils.arrayFilter(self.Model.CurrentStep().Files(), function (item) {
        total += item.RawSize;
    });
}

如果 self.Model.CurrentStep() 的类型等于 5,那么它永远不会有 Files 成员,因为 JavaScript 数字与Files。换句话说,要么你的if语句错误,要么你过滤的数组错误。

也许你的意思是你的 if 语句是:

if (self.Model.CurrentStep().length === 5)