0

我有过去 24 个月从服务器返回的记录列表。有一个选择菜单,用户可以在其中选择“过去 18 个月”、“过去 12 个月”或“过去 24 个月”。

默认为 24​​ 个月,因此当用户第一次访问该页面时,将从服务器检索完整列表。现在,不使用回发(从而节省到服务器的行程),我可以根据用户从选择菜单中选择的内容过滤数据吗?

我将 ASP.NET MVC4 与 jQuery mobile 和 knockout.js 一起使用。

视图中的表(html):

        <table style="width:100%;">

<tbody data-bind="foreach: TankMixRows">
    <tr>
        <td data-bind="text: ProductName"></td>
        <td data-bind="text: AI"></td>
        <td></td>
        <td data-bind="text: MOAHerbicide"></td>
        <td data-bind="text: MOAInsecticide"></td>
        <td data-bind="text: MOAFungicide"></td>
    </tr>
</tbody>
    </table>

Javascript:

  function MOAViewModel() {
var self = this;

self.TankMixRows = ko.observableArray([]);

self.getTankMixRows = function () {
  $.ajax({
    type: "GET",
    url: '@Url.Action("jsonModeOfAction", "WorkOrders")',
    data: {
      ID: '@Model.RecFieldId'
    },
    success: function (data) {
      self.TankMixRows(data);
    }
  });
}

//Load initial state from server and populate viewmodel
self.getTankMixRows();
  }

  ko.applyBindings(new MOAViewModel());
4

1 回答 1

1

首先,您需要在客户端模型中花费时间。一旦你有了它,你将需要日期过滤器的选项。将此绑定到 viewModel 中的可观察对象。让我们称之为:

self.filterDateSelection = ko.observable(24);

然后您可以创建一个过滤数据的计算数组:

self.filteredItems = ko.computed(function() {
    return ko.utils.arrayFilter(self.TankMixRows(), function(row) {
        // Filter logic here;
        // Return true if you want to keep the record
        // Use row.date and self.filterDateSelection()
        return true;

    });    
}

而是将您的视图绑定到filteredItems。

MVC 的默认 DateTime 序列化可能会与您发生冲突。看看: 将 .NET DateTime 转换为 JSON


更新

看看下面的小提琴:http: //jsfiddle.net/mrfunnel/9eaMY/

我使用Moment.js来帮助处理 javascript 日期。

您可以将上述选项绑定用于月份过滤器,以将逻辑保留在 Knockout 中并简化过滤器范围的计算。

// Possible options
self.filterMonths = ko.observableArray([12, 18, 24]);
// Selected option
self.chosenFilter = ko.observable(24);

这在视图中绑定如下:

<p>Choose Month Filter:
    <select data-bind="options: filterMonths, value: chosenFilter"></select>
</p>

现在我们可以在每次 selectedFilter 更改时计算 filterDate:

self.filterDate = ko.computed(function () {
    var d = moment().subtract('months', self.chosenFilter());
    return d;
});

然后可以按如下方式计算过滤的项目:

self.filteredItems = ko.computed(function () {
    return ko.utils.arrayFilter(self.tankMixRows(), function (row) {
        // Filter logic here;
        // Return true if you want to keep the record
        return row.date > self.filterDate();
    });
});
于 2013-08-19T22:40:01.433 回答