我有以下代码来加载带有dropdownlist
数据的json
$('#btnAddNew').click(function (evt) {
$.ajax({
url: '@Url.Action("GetAllEmployee","Employee")',
method: 'GET',
dataType: 'json',
success: function (data) {
//edit form's ddl
$('#ddlEmployeeCategories').empty();
console.log(data);
$(data).each(function (index, item) {
//edit forms ddl
$('#ddlEmployeeCategories').append($('<option/>', { text: item.Description, value: item.ID }));
});
},
error: function () { }
});
$('#empID').val('');
$('#ddlEmployeeCategories').val('2');
$('#txtFirstName').val('');
$('#txtLastName').val('');
$('#txtDOB').val('');
$('#txtSalary').val('');
$('#cbIsMarried').prop('checked', false);
form.dialog('open');
resetValidations();
form.show();
});
第$('#ddlEmployeeCategories').val('2');
行将所选项目设置为值&#39; 2&#39; (不是指数)。但这不会设置所选项目。为什么呢?
答案 0 :(得分:1)
将您的success
更改为:
success: function (data) {
$('#ddlEmployeeCategories').empty();
$(data).each(function (index, item) {
$('#ddlEmployeeCategories').append($('<option/>', { text: item.Description, value: item.ID }));
});
$('#ddlEmployeeCategories').val('2');
... // your other code
}
当您确定ajax呼叫已完成时,您必须设置该项目。
答案 1 :(得分:1)
在ajax调用返回成功后修改值:
$('#btnAddNew').click(function(evt) {
$.ajax({
url: '@Url.Action("GetAllEmployee","Employee")',
method: 'GET',
dataType: 'json',
success: function(data) {
//edit form's ddl
$('#ddlEmployeeCategories').empty();
console.log(data);
$(data).each(function(index, item) {
//edit forms ddl
$('#ddlEmployeeCategories').append($('<option/>', {
text: item.Description,
value: item.ID
}));
});
$('#empID').val('');
$('#ddlEmployeeCategories').val('2');
$('#txtFirstName').val('');
$('#txtLastName').val('');
$('#txtDOB').val('');
$('#txtSalary').val('');
$('#cbIsMarried').prop('checked', false);
form.dialog('open');
resetValidations();
form.show();
},
error: function() {}
});
});