Knockout foreach with a where clause

2019-08-24 03:07发布

This sytax is in razor that I am converting to knockoutJS.. any help much appreciated..

Where ItemStatus.Active is 0 in an enum in c# ( backend )

@foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{   
  <div class="someclass”>
  <span class="label">Name:</span>
  <span class="value">@employee.Name</span> 
  </div>
}

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

Thank you

2条回答
小情绪 Triste *
2楼-- · 2019-08-24 03:36

Razor runs server-side. So, you can't use Employees with knockout bindings which are apllied client-side. You need to hand over this Employees data to a javascript variable, and then bind that using knockout which will run client-side, after the page loads.

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script>
    // cretes a js array of active employees
    var activeEmployees = @Html.Raw(JsonConvert.SerializeObject(Employees.Where(x => x.Status == ItemStatus.Active)));

    var viewModel = {
      Employees: ko.observableArray(activeEmployees)
    }

    ko.applyBindings(viewModel);
</script>

Use the foreach binding in your HTML like this (Here Employees refers to the property of your knockout viewModel, not MVC)

<!-- ko foreach: Employees -->
<div class="someclass">
  <span class="label">Name:</span>
  <span class="value" data-bind="text:Name"></span>
</div>
<!-- /ko -->

You also need to add @using Newtonsoft.Json to the top your cshtml file for JsonConvert

查看更多
Summer. ? 凉城
3楼-- · 2019-08-24 03:37

Any JavaScript expression can be used in Knockout bindings.

So you could use the filter function (ES6):

<!-- ko foreach: Employees.filter(employee => employee.Status == 0) -->
...
<!-- /ko -->

Or any other method of filtering:

<!-- ko foreach: ko.utils.arrayFilter(Employees.filter, function(employee) { return employee.Status == 0; }) -->
...
<!-- /ko -->
查看更多
登录 后发表回答