Reputation: 103
I've setup Select2 in a form to create a list of strings. It also allows me to search and create my own items.
@Html.ListBoxFor(model => model.Schemas, new SelectList(Model.Schemas, "", ""), new { id = "schema-select" })
My Jquery to initialise the control is:
$('#schema-select').select2({
theme: "bootstrap-5",
width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
placeholder: $(this).data('placeholder'),
closeOnSelect: false,
tags: true,
ajax: {
dataType: 'json',
url: '/Select2/FetchSchemas',
delay: 250, // wait 250 milliseconds before triggering the request
minimumInputLength: 2,
data: function (params) {
var query = {
schema: params.term
}
// Query parameters will be ?search=[term]
return query;
},
processResults: function (data) {
// Transforms the top-level key of the response object from 'items' to 'results'
return {
results: $.map(data, function (item) {
return {
id: item.text,
text: item.text,
}
})
};
}
}
});
I also have this method:
[HttpGet]
public JsonResult FetchSchemas(string schema)
{
List<viewSchemaList> list = new List<viewSchemaList>();
if (!string.IsNullOrEmpty(schema))
{
list = db.viewSchemaList.Where(x => x.text.StartsWith(schema)).ToList();
}
else
{
list = db.viewSchemaList.ToList();
}
return Json(list, JsonRequestBehavior.AllowGet);
}
Everything works fine for creating a record but I'm struggling to get it to work for editing the list. Is this even possible using a ListBoxFor or do I need to change it to use the html SELECT tag?
Upvotes: 0
Views: 8