Arriving a bit tardy to the event, I encountered a similar issue.
I needed to implement a select2-multiselector that loaded data via ajax. Therefore, some adjustments were necessary.
To achieve this, you can include the following JavaScript and CSS:
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c1d7ded7d1c680f2869c829c829c8380">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8efdebe2ebedfabccebaa0bea0bfbc">[email protected]</a>/dist/js/select2.min.js"></script>
In my View (where the model is an IEnumerable
):
...
@for (int index = 0; index < Model.Count; index++)
{
<div>
<input type="hidden" asp-for="@Model[index].Id"/>
<input type="text" asp-for="@Model[index].Title">
<select class="js-example-basic-multiple" style="width: 100%;" asp-for="@Model[index].TagIds" multiple="multiple">
@foreach (TagDetailModel tag in Model[index].Tags)
{
<option value="@tag.Id" selected="selected">@tag.Name</option>
}
</select>
</div>
}
...
Here's what I did:
I inserted a select
in the view, assigned it a class for later JavaScript access. If multiple values are needed, add multiple="multiple"
.
In the model, I included tags that were already assigned to the model. These tags aren't automatically added with select2, so manual addition is required. If multiple selection is disabled, your Tags
may contain only one Tag
and no enumeration is necessary.
$(document).ready(function() {
$('.js-example-basic-multiple').select2({
ajax: {
url: '/Tag/GetTags',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}
}
});
});
In this script, upon full document load, the select
elements are transformed into select2 elements using
$('.js-example-basic-multiple').select2()
. I utilized ajax to load options dynamically. However, if ajax is not desired, static values can be added in the view using
<option value="@tag.Id">@tag.Name</option>
.
In my controller (specifically in ImageController.cs
within my application), I simply added a function for handling the ajax-request:
public async Task<JsonResult> Tags(int id)
{
return Json(await _imageService.Get(id));
}