如何以编程方式将值设置为 Select2 jQuery 和 ASP .Net Core



我正在做一个asp.net Core项目,我第一次使用Select2。

我有一个页面,我通过ViewModel传递我需要的ID,像这样:

控制器:

public async Task<IActionResult> MyPage()
{
var model = new MyViewModel()
{
selectedUSerId = 1,
selectedEmployeeId =1
};
return View(model);
}

视图:

@model MyViewModel
<select class="form-select" id="User" name="User" data-url="@Url.Action("MyUserAction","MyUserController")" data-placeholder="@Localizer["SelectUser"].Value">
<option></option>
</select>
<select class="form-select" id="Employee" name="Employee" data-url="@Url.Action("MyEmployee","MyEmployeeController")" data-placeholder="@Localizer["SelectUser"].Value">
<option></option>
</select>

@section Scripts{
<script type="text/javascript">
var userId = "@Model.selectedUSerId";
var emplyeeId = "@Model.selectedEmployeeId";
$(document).ready(function () {

$('select').each(function () {
InitSelect2(this.id);

});
if(userId){
$('#User').val(userId).trigger('change');
}
if(emplyeeId){
$('#User').val(emplyeeId).trigger('change');
}
});

function InitSelect2(selector, selectedId = 0) {
var url = $("#" + selector).data('url');
var placeholder = $("#" + selector).data('placeholder');
const type = "POST";
const dataType = "json";
if (!url) {
console.error("Selector: " + selector + " Unspecified URL");
return;
}
if (placeholder === "") {
console.error("Selector: " + selector + " Unspecified Placeholder");
return;
}
try {
$("#" + selector).select2({
theme: "bootstrap-5",
width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
placeholder: placeholder,
allowClear: true,
minimumInputLength: 3,
ajax: {
url: url,
type: type,
dataType: dataType,
delay: 250,
data: function (params) {
var query = {
id: selectedId,
searchFullName: params.term,
}
return query;
},
processResults: function (data) {
console.log(data)
return {
results: data.results
};
},
}
})
} catch (ex) {
console.error(ex);
}
}
</script>
}

目前运行良好。

但是当我尝试做:

$('#User').val(userId).trigger('change'); or
$('#Employee').val(emplyeeId ).trigger('change');

什么也没有发生。

我认为只有当我第一次点击下拉列表检索数据时才会起作用,而不是每次点击时都这样做。这样我就有了<option>s,我可以使用jQuery通过Id来选择<option>

我不喜欢采用这种方法,因为数据应该动态加载和设置。没有别的办法了吗?

如果你想做的事情只有当第一次被选中的值被改变,你可以尝试使用一个js变量,改变它的值当第一次被选中的值被改变。这里是一个示例,只有当第一次改变所选值时,才会调用alert(1)

var UserCount = 0;
var EmplyeeCount = 0;

$('#User').change(function() {
if (UserCount == 0) {
UserCount++;
alert(1);
}
});
$('#Employee').change(function() {
if (EmplyeeCount == 0) {
EmplyeeCount++;
alert(1);
}
});

最新更新