をおそらく以下のコードが適用されます:
/*
* @param url = URL to fetch data (i.e. controller action method
* returning IEnumerable<SelectListItem> or SelectList)
* @param source = source dropdownlist name
* @param target = target dropdownlist name
*/
function cascadeDropDownList(url, source, target) {
$.ajax({
type: 'POST',
url: url,
data: { Id: $('#' + source).val() },
dataType: 'json',
traditional: true,
success: function (data) {
// remove previous option contents first
$('#' + target + ' option').each(function() {
$(this).remove();
});
// add new option contents
var options = '<option value="">--Seçin--</option>';
for (var i = 0; i < data.length; i++) {
options += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
$('#' + target).html(options);
}
});
}
change
のイベントでの使用:
$(document).ready(function() {
$('#ddlIl').change(function() {
var url = '/Users/GetIlce'; // recommended: '@Url.Action("GetIlce", "Users")'
var source = $(this).attr('id');
cascadeDropDownList(url, source, 'ddlIlce');
});
});
NB:上記の機能はすでにビューページで作成され、あなただけのselect
要素を再作成せずに、オプション要素の値を挿入するたドロップダウンリストのターゲットを想定しています。あなたが代わりに新しいターゲットドロップダウンリストを作成したい場合は、機能下記のように変更します。
/*
* @param url = URL to fetch data (i.e. controller action method
* returning IEnumerable<SelectListItem> or SelectList)
* @param source = source dropdownlist name
* @param target = target element (e.g. div)
* @param ddlName = target dropdownlist name
*/
function cascadeDropDownList(url, source, target, ddlName) {
$.ajax({
type: 'POST',
url: url,
data: { Id: $('#' + source).val() },
dataType: 'json',
traditional: true,
success: function (data) {
var ddl = "<select id='" + ddlName + "'>";
ddl += '<option value="">--Seçin--</option>';
for (var i = 0; i < data.length; i++) {
ddl += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
ddl += '</select>';
$('#' + target).html(ddl);
}
});
}
使用法:
$(document).ready(function() {
$('#ddlIl').change(function() {
var url = '/Users/GetIlce'; // recommended: '@Url.Action("GetIlce", "Users")'
var source = $(this).attr('id');
var target = $('#targetdiv').attr('id');
cascadeDropDownList(url, source, target, 'ddlIlce');
});
});
の作業例:.NET Fiddle
おかげで、まさに私が必要なもの – Ismael123