Populate Bootstrap Multiselect Options with JSON and Spring MVC

This is the second post on the role of Spring MVC and JSON in a JQuery Plugin called Bootstrap Multiselect. In our previous post we covered posting the selected values to a Spring MVC endpoint with JSON. Today we're going to see how to dynamically populate the HTML Multiselect <Option /> items with JSON and Spring MVC.

Here's the Bootstrap Multiselect on the NixMash Spring Demo Site. Since I added Bootstrap Badge display (the circled “2” indicator below) we call it Badge Boy.

As I mentioned in the previous post, the only function of Badge Boy is to demonstrate Spring MVC interplay with client-side JavaScript Components. We still aren't saving the selections on the server, but populating the selection options dynamically with JSON and Spring MVC gets us one step closer if we wished to do so.

The Multiselect Plugin includes the ability to assign the selection options from a JSON datasource. Our Spring MVC method is below. As you see there's very little to do in this simple GET request. @ResponseBody and Jackson Object Conversion Library in our Spring Configuration (not shown) produce JSON for us.

We're using a simple SelectOptionDTO class to hold our <Options /> Label, Value and Selected values. badgeSelectOptions() populates our List<SelectOptionDTO> object, some of which is shown below as well. selectOptionDTOs.add(new SelectOptionDTO(…)).

The resulting JSON looks like this. And yes, the labels and values can be different. They're the same here only to simplify generating the postback message.

The JavaScript is shown next. Most of the code is folded but you can see the relevant lines that handle the JSON <OPTION /> data.  We're wrapping the .multiselect functions on the #multiselect-badgeboy <SELECT /> control inside a $.getJSON(), passing the JSON data to the .multiselect function's ‘dataprovider' property. This wrapping design also prevents the Synchronous XMLHttpRequest on the main thread is deprecated warning from appearing in the Chrome Developer Console.

As I said at the top, the Badge Boy widget is on the NixMash Spring Demo Site. All source code discussed in this post is available in v0.2.1 of NixMash Spring on GitHub.

Posted October 02, 2015 02:25 PM EDT

More Like This Post