I am currently utilizing a Select2 input box as a tag controller in my view:
CSHTML
<input id="tagSelector" type="hidden" style="width: 300px"/>
JS
$('#tagSelector').select2({
placeholder: 'Select a tag...',
multiple: true,
ajax: {
url: '@Url.Action("SearchTags", "UnitDetails")',
dataType: 'json',
data: function(term, page) {
return {
searchTerm: term
};
},
results: function(data, page) {
return { results: data };
}
},
createSearchChoice: function(term) {
return { id: term, text: term };
}
}).on("removed", function(e) {
var url = '@Url.Content("~/UnitDetails/UnTagUnit/" + Model.ViewUnitContract.Id)';
var id = e.val;
var tagName = e.choice.text;
console.log(id + " : " + tagName);
$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function() {
},
error: function() {
}
});
})
.on("select2-selecting", function(e) {
var url = '@Url.Content("~/UnitDetails/TagUnit/" + Model.ViewUnitContract.Id)';
var id = e.val;
var tagName = e.object.text;
console.log(id + " : " + tagName);
$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function() {
},
error: function() {
}
});
});
});
C#
public JsonResult GetInitialTags(int id)
{
Model = new UnitDetailsModel(UnitClient.GetUnit(id));
foreach (var tag in Model.ViewUnitContract.Tags)
{
Model.TagsSelected.Add(tag);
}
var result = Model.TagsSelected.Select(a => new
{
id = a.Id,
text = a.Name
});
return Json(result, JsonRequestBehavior.AllowGet);
}
I am currently struggling with implementing the initSelection
method to pre-fill the input box with already selected tags. Any guidance on this matter would be greatly appreciated, as I am finding it quite challenging at the moment :)