Ajax範例-動態更新三層下拉選單

動態改變下拉選單的前後端程式碼範例

參考來源:mrkt – ASP.NET MVC 3 – 基本三層連動式下拉選單應用

前端頁面的三個下拉選單Page, Area, Type

View:

<tr>
	<td>頁面名稱:</td>
	<td>
		<select id="Page" name="Page" class="form-control">
			<option>請選擇頁面</option>
			<% foreach (var item in Model.BannerSelection.PageNameDict) { %>
			<option value="<%=item.Value.Page_ID %>"><%=item.Value.Page_Description %></option>
			<% } %>
		</select>
	</td>
</tr>
<tr>
	<td>區塊名稱:</td>
	<td>
		<select id="Area" name="Area" class="form-control">
			<option>------</option>
		</select>
	</td>
</tr>
<tr>
	<td>類型名稱:</td>
	<td>
		<select id="Type" name="Type" class="form-control">
			<option>------</option>
		</select> <label id="ImageFormatMsg"></label>
	</td>
</tr>

js:

var imageFormatMsgAry = [];
var ajaxAreaUrl = '/BackBanner/getAreaList';
var ajaxTypeUrl = '/BackBanner/getTypeList';
 
$(document).ready(function () {
    $('#Page').change(function () { ChangePage(); });
    $('#Area').change(function () { ChangeArea(); });
    $('#Type').change(function () { ChangeType($('#Type option:selected').val()); })
})
         
function ChangePage() {
    // 清除下層的下拉選單後重新載入
    $('#Area').empty().append($('<option></option>').val('').text('------'));
    $('#Type').empty().append($('<option></option>').val('').text('------'));
    $('#ImageFormatMsg').html('');
    // Area Key
    var selectText = $('#Page option:selected').text();
    if ($.trim(selectText).length > 0 && selectText != "請選擇頁面")
        getAreaList(selectText);
}
 
function ChangeArea() {
    // 清除下層的下拉選單後重新載入
    $('#Type').empty().append($('<option></option>').val('').text('------'));
    $('#ImageFormatMsg').html('');
    // Type Key
    var selectText = $('#Area option:selected').text();
    if ($.trim(selectText).length > 0 && selectText != "請選擇區塊" && selectText != "------")
        getTypeList(selectText);
}
 
function ChangeType(typeValue) {
    if (typeValue == "")
        $('#ImageFormatMsg').html('');
    else
        $('#ImageFormatMsg').html('<font color="red">' + imageFormatMsgAry[typeValue] + '</font>');
}
 
function getAreaList(areaKey)
{
    $.ajax({
        url: ajaxAreaUrl,
        data: { areaKey: areaKey },
        type: 'post',
        cache: false,
        async: false,
        dataType: 'json',
        success: function (data) {
            if (data.length > 0) {
                $('#Area').empty();
                $('#Area').append($('<option></option>').val('').text('請選擇區塊'));
                $.each(data, function (i, item) {
                    $('#Area').append($('<option></option>').val(item.Key).text(item.Value));
                });
            }
        }
    });
}
 
function getTypeList(typeKey)
{
    imageFormatMsgAry = [];
    $.ajax({
        url: ajaxTypeUrl,
        data: { typeKey: typeKey },
        type: 'post',
        cache: false,
        async: false,
        dataType: 'json',
        success: function (data) {
            if (data.length > 0) {
                $('#Type').empty();
                $('#Type').append($('<option></option>').val('').text('請選擇類型'));
                $.each(data, function (i, item) {
                    $('#Type').append($('<option></option>').val(item.Key).text(item.Value.Value));
                    imageFormatMsgAry[item.Key] = item.Value.Key;
                });
            }
        }
    });
}

Function in Controller:

#region Ajax請求處理
/// <summary>
/// 新增頁面 - 區塊清單
/// </summary>
/// <param name="areaKey"></param>
/// <returns></returns>
public JsonResult getAreaList(string areaKey)
{
    List<KeyValuePair<string, string>> items = new List<KeyValuePair<string, string>>();
    if (BannerSelection.AreaNameDict.ContainsKey(areaKey))
    {
        foreach (var item in BannerSelection.AreaNameDict[areaKey])
            items.Add(new KeyValuePair<string, string>(item.Key.ToString(), item.Value));
    }
 
    return this.Json(items);
}
 
/// <summary>
/// 新增頁面 - 類型清單
/// </summary>
/// <param name="typeKey"></param>
/// <returns></returns>
public JsonResult getTypeList(string typeKey)
{
    List<KeyValuePair<string, KeyValuePair<string, string>>> items = new List<KeyValuePair<string, KeyValuePair<string, string>>>();
    if (BannerSelection.TypeNameDict.ContainsKey(typeKey))
    {
        foreach (var item in BannerSelection.TypeNameDict[typeKey])
        {
            items.Add(new KeyValuePair<string, KeyValuePair<string, string>>(item.Id, new KeyValuePair<string, string>(item.ImageFormatMsg, item.Value)));
        }
    }
    return this.Json(items);
}
#endregion