将值设置为select2下拉列表,该下拉列表是从ASP.NET MVC中的数据库中检索的


<script type="text/javascript">
$(document).ready(function () {
//following values i retrived from database and i want to display into select2 dropdown
var selectedValue1 = '43,48,47,57'; 
$('#ddlCity1').select2({
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
dataType: 'json',
delay: 250,
url: '@Url.Action("GetCityList", "DemoMVC")',
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.City
});
});
return { results: newData };
},
cache: true
},            
});
$(".city1").on("select2:select", function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
$('.city1').on('select2:unselect', function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values

});

});

//Dropdown with select2 control
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>City</label>
<select id="ddlCity1" class="city1" style="width:500px"></select>
</div>
</div>
</div>

我假设这个动作"GetCityList";返回json

$('#ddlCity1').select2({ minimumInputLength: 0, //for listing all records > set 0 
maximumInputLength: 20, //only allow terms up to 20 characters long 
multiple: true, 
placeholder: "Select", 
allowClear: true, 
tags: false, //prevent free text entry 
width: "100%"
});
function ("/DemoMVC/GetCityList", {}, "json", success, falier) {
$.ajax({
url: url,
data: paramters,
contentType: "application/json; charset=utf-8",
dataType: returnFormat,
success: function (data) {
success(data);
let htmlData = "<option value='' selected disabled hidden>Select City...</option>";

for (let i = 0; i < Object.values(data)[1].length; i++) {
htmlData = htmlData + Template(Object.values(data)[1][i]);
}
$("#ddlCity1").html(htmlData);
},

error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText + ': ' + xhr.responseText + ': ';
console.log('Error - ' + errorMessage);
},
type: 'GET',
});
}
function Template(item) {
let itemHtml = "<option value='" + item.id + "'>" + item.city + "</option>";
return itemHtml;
}

最新更新