As per the title I am using the latest select2 select box on a HTML5 page and using their example I am making a call to a Web API 2 endpoint I created.
For testing purposes the endpoint simply builds a collection of Tags and returns the result as a HttpResponseMessage. Here is some code to visualise it all:
The Tag entity
public class TagData
{
public string Id { get; set; }
public string Text { get; set; }
}
The model:
public class TagsModel
{
public IEnumerable<TagData> Tags { get; set; }
}
The controller action in the Web API 2 project:
public IHttpActionResult Get()
{
var tags = new TagsModel()
{
Tags = new List<TagData>
{
new TagData()
{
Id = "1",
Text = "Tag1"
},
new TagData()
{
Id = "2",
Text = "Tag2"
}
}
};
return Ok(tags);
}
I knocked up a unit test and it all works also running a test in Fiddler4 using composer returns the following JSON response:
{"Tags":[{"Id":"1","Text":"Tag1"},{"Id":"2","Text":"Tag2"},{"Id":"3","Text":"Tag3"}}]}
In the HTML5 page I dropped in the standard select2 html element:
<select class='s2-search-box form-control' multiple='multiple'></select>
The idea here is to bind the select2 control to remote data then use the tagging feature to allow the user to find a tag, select it and repeat so this is done using this ajax call:
$(document).ready(function () {
$(".s2-search-box").select2({
ajax: {
url: "http://localhost:54850/api/s2demo",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.Tags
};
},
cache: true
}
});
});
So far so good, my unit tests work and when I used Firebug to inspect the ajax call I can see data being returned in the correct format and I am able to display the data.Tags collection so I know the data is there however the actual select2 dropdown displays a list of 'undefined' items and doesn't actually display the data I want or allow me to create the tags from those selections.
As a side note I tried this as well:
$(".s2-search-box").select2({
ajax: {
url: "http://localhost:54850/api/s2demo",
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.Text,
id: item.Id
}
}),
pagination: {
more: data.more
}
};
}
}
});
This works in that I can create the tags so they appear in the select2 control as :
tag1[x] tag2[x]
However the dropdown list is permanently displayed.
I am using the latest 4.0.2 version of the select2 library.
Thanks in advance.
T