Asp.net-mvc – How to display No Data when observable array is empty

asp.net-mvcknockout.js

I'm new to Knockout.js and I'm trying to display data from observable array to a table.
The problem I have is it generates two tbody tags. But if I move the empty check logic into the foreach: loop, the No Data does showup at all.

Is there a better way to do this using table? I don't like to use ul or ol in this case.

<table>
    <thead>
        <tr>
            <th>Permit</th>
            <th>Region</th>
            <th>Landowner</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: requestList">
        <tr>
            <td><span data-bind="text: permit"></span></td>
            <td><span data-bind="text: region"></span></td>
            <td><span data-bind="text: landowner"></span></td>
        </tr>
    </tbody>
    <tbody data-bind="if: requestList().length === 0">
        <tr>
            <td colspan="3">No Data</td>
        </tr>
    </tbody>
</table>

Best Answer

When doing this we make a lot of use of virtual elements. They are outlined here http://knockoutjs.com/documentation/if-binding.html#note_using_if_without_a_container_element

The rest of your markup is fine, but you could wrap your first tbody in a virtual element like this:

<!-- ko if: requestList().length -->
    <tbody data-bind="foreach: requestList">
        <tr>
            <td><span data-bind="text: permit"></span></td>
            <td><span data-bind="text: region"></span></td>
            <td><span data-bind="text: landowner"></span></td>
            <td><button data-bind="click: $parent.remove">Remove</button></td>
        </tr>
    </tbody>
<!-- /ko -->

JSFiddle here: http://jsfiddle.net/ZKWMh/

Related Topic