[英]MVC 5 - After setting a dropdown option to selected on document ready, why does it get reset?
In my MVC 5 application, I am trying to choose a selection from a dropdown on document ready. 在我的MVC 5应用程序中,我试图从准备好文档的下拉列表中选择一个选项。 This is on an edit view that gets populated with values depending on the chosen item.
这是在一个编辑视图中,该视图中填充了取决于所选项目的值。 The
FillLocations
function is basically a way to fill up the Location
dropdown with values depending on which facility is selected. FillLocations
函数基本上是一种根据选择的设施用值填充“ Location
下拉列表的方法。 I set up an alert to pop up to confirm that there is the selection I am trying to make in the list of options, and it works as expected. 我设置了一个警报以弹出弹出窗口,以确认在选项列表中我正在尝试进行选择,并且它可以按预期工作。 I even see the option being selected for a very quick moment before it chooses the empty default option.
在选择空的默认选项之前,我什至会很快看到该选项被选中。
JavaScript: JavaScript的:
$(document).ready(function () {
if ($('#Location').val() == "") {
FillLocations();
} else {
var loc = $('#Location option:selected').text();
FillLocations();
$("#Location option").each(function () {
if ($("#Location").text() == loc) {
$("#Location").attr('selected', true);
alert("The selection is there.");
}
});
}
});
function FillLocations() {
var selectedFacility = $("#Facility").val();
if ($('#Usage_Status').val() == 2) {
$.ajax({
type: "Post",
url: "@Url.Action("GetLocations", "Item")",
data: { Facility: selectedFacility },
dataType: 'json',
success: function (data) {
//Clear dropdown data and add new values using ajax
$('#Location').empty();
$('#Location').append('<option value=""></option>');
for (var i = 0; i < data.length; i++) {
$('#Location').append('<option value="' + data[i].Value + '">' + data[i].Text + '</option > ');
}
}
});
}
}
The code after your call to FillLocations is running before FillLocations() is finished and has populated the select. 调用FillLocations之后的代码在FillLocations()完成并填充选择之前正在运行。 Try moving the code into the ajax success function like so:
尝试将代码移动到ajax成功函数中,如下所示:
$(document).ready(function () {
FillLocations();
});
function FillLocations() {
var selectedFacility = $("#Facility").val();
if ($('#Usage_Status').val() == 2) {
$.ajax({
type: "Post",
url: "@Url.Action("GetLocations", "Item")",
data: { Facility: selectedFacility },
dataType: 'json',
success: function (data) {
var loc = $('#Location').val();
//Clear dropdown data and add new values using ajax
$('#Location').empty();
$('#Location').append('<option value=""></option>');
for (var i = 0; i < data.length; i++) {
$('#Location').append('<option value="' + data[i].Value + '">' + data[i].Text + '</option > ');
}
$("#Location option").each(function () {
if ($(this).attr("value") == loc) {
$(this).prop('selected', true);
alert("The selection is there.");
}
});
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.