Вы можете попробовать следующее:
//1. Action Method Which Returns the data.
public ActionResult GetSelect2Data(string query)
{
//In Realtime This should come from the Database
List<DropDownItem> collection = new List<DropDownItem>() {
new DropDownItem(){ Value = 1, Text = "Switzerland"},
new DropDownItem(){ Value = 2, Text = "Canada"},
new DropDownItem(){ Value = 3, Text = "Japan"},
new DropDownItem(){ Value = 4, Text = "Germany"},
new DropDownItem(){ Value = 5, Text = "Australia"},
new DropDownItem(){ Value = 6, Text = "United Kingdom"},
new DropDownItem(){ Value = 7, Text = "United States"},
new DropDownItem(){ Value = 8, Text = "Sweden"},
new DropDownItem(){ Value = 9, Text = "India"},
new DropDownItem(){ Value = 10, Text = "Russia"},
};
var searchResult = from c in collection
where c.Text.Contains(query,
StringComparison.CurrentCultureIgnoreCase)
select c;
return Json(searchResult.ToList());
}
///2. JS Method which binds any HTML Select as Select2 or Smart Select.
///In the User Interface (.cshtml file)You may define a framework JS Function as which could be used anywhere
function registerSelect2(dropDownSelector, ajaxUrl) {
$(dropDownSelector).select2({
ajax: {
url: ajaxUrl,
dataType: 'json',
delay: 10,
type: 'GET',
data: function (params) {
return {
query: params.term, // search term
};
}
, processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.value,
text: item.text,
};
})
};
},
cache: true,
},
minimumInputLength: 3,
allowHtml: true,
allowClear: true
});
}
//3. Invoke the JS Function to make any particular Select a Select2.
$(function () {
//Just you need to pass the Selector of your control and the Ajax Url from which data has to be loaded
registerSelect2("#ddlSelect2", "/user/GetSelect2Data");
});
//This is the Simple Select which's made a Select2 Control. Paste it somewhere in the UI
<select id="ddlSelect2"></select>