Bootstrap Table is the best way I’ve found of adding additional functionality to HTML tables. One of the nice features about it is that it will load data from a URL if it’s provided in the correct JSON format which allows the data provision to be decoupled from the page rendering.

Although it’s not immediately apparent what format this JSON response needs to be in there’s a few examples here and it seems like it should be something like the below.

{
    "total": 200,
    "rows": [
        {
            "id": 0,
            "name": "Item 0",
            "price": "$0"
        },
        {
            "id": 1,
            "name": "Item 1",
            "price": "$1"
        }
    ]
}

The same data returned by my OData API looks like this.

{
	"@odata.context": "https://localhost:44366/api/$metadata#Items",
	"@odata.count": 20,
	"value": [
        {
            "id": 0,
            "name": "Item 0",
            "price": "$0"
        },
        {
            "id": 1,
            "name": "Item 1",
            "price": "$1"
        }
	]
}

Although this is different from the OData structure it’s possible to format the returned OData JSON in the format expected by Bootstrap Table using the responseHandler.

function responseHandler(res) {
	return {
		total: res['@@odata.count'],
		rows: res.value
	};

It’s also necessary to update the query parameters that Bootstrap Table uses to navigate the data as the names don’t align with those required by OData, this can be done using the queryParams option.

function queryParams(params) {
	return {
		$top: params.limit,
		$skip: params.offset,
		$search: params.searchText,
		$sort: params.sortName,
		$order: params.sortOrder,
		$count: true
	};
}

A new variable called $count is added to the URL parameters to request a count of the total rows available.

The below table code will then produce a table using our OData API as the source.

<table id="table"
	   data-toggle="table"
	   data-pagination="true"
	   data-side-pagination="server"
	   data-search="true"
	   data-query-params="queryParams"
	   data-response-handler="responseHandler"
	   data-url="@Url.Action("Items", "Api")">
	<thead>
		<tr>
			<th data-field="id" data-sortable="true">ID</th>
			<th data-field="name" data-sortable="true">Name</th>
			<th data-field="price" data-sortable="true">Price</th>
		</tr>
	</thead>
</table>

Example code for accessing an OData source from a Bootstrap table can be found here.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *