You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于首个下拉框动态展示第二个下拉框选项的技术实现问询

Implement Dependent Dropdown (Error Type → Class Type)

Got it, let's fix up your form so the Class Type dropdown only shows relevant options based on the selected Error Type. Here's a step-by-step breakdown of what needs to change:

1. Update Backend to Support Filtered Class Data

First, we need to modify your GetClassCategory endpoint to accept an Error identifier (like errorCode) so it can return only the Class options linked to that specific Error.

// Updated GetClassCategory method with a filter parameter
public JsonResult GetClassCategory(string errorCode) {
    // Replace with your actual data access logic to fetch Classes by ErrorCode
    List<ErrorClass> filteredClasses = errorDataAccessLayer.GetClassesByErrorCode(errorCode);
    
    return Json(filteredClasses.Select(x => new { 
        classCode = x.ClassCode, 
        classDescription = x.ClassDescription 
    }).ToList(), JsonRequestBehavior.AllowGet);
}

Make sure you add a GetClassesByErrorCode method in your errorDataAccessLayer that queries the database for Class records associated with the provided errorCode (using whatever foreign key relationship exists between your Error and Class tables).

2. Tweak the View for Better UX

Let's set the Class Type dropdown to be disabled by default (since it shouldn't be usable until an Error is selected) to guide users:

<form id="ticket_form" method="post" enctype="multipart/form-data">
    <div class="row">
        <div class="form-group col-md-4">
            <label><strong>Error Type</strong></label>
            <select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
            </select>
        </div>
    </div>
    <div class="row">
        <div class="form-group col-md-4">
            <label><strong>Class Type</strong></label>
            <!-- Disabled by default until a valid Error is chosen -->
            <select name="ClassType" id="ClassDropdown" class="form-control ClassType" disabled>
                <option value="-1">Select an Error Type first</option>
            </select>
        </div>
    </div>
    <div class="form-group">
        <input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
    </div>
</form>

3. Rewrite JavaScript for Dynamic Loading

We'll remove the initial load of the Class dropdown and instead load its options only when the user selects a relevant Error Type. Also, I'd recommend using errorCode as the dropdown value (instead of errorDescription) since codes are more stable for database queries:

<script>
$(document).ready(function () {
    // Load Error Type dropdown on page load
    $.ajax({
        type: "POST",
        url: "/Ticket/GetErrorCategory",
        data: "{}",
        success: function (data) {
            let options = '<option value="-1">Please Select Error Type</option>';
            data.forEach(error => {
                // Use errorCode as the value for more reliable filtering
                options += `<option value="${error.errorCode}">${error.errorDescription}</option>`;
            });
            options += '<option value="Others">Others</option>';
            $("#ErrorDropdown").html(options);
        }
    });

    // Listen for changes to the Error Type dropdown
    $("#ErrorDropdown").on("change", function() {
        const selectedError = $(this).val();
        const classDropdown = $("#ClassDropdown");

        // Reset Class dropdown state
        classDropdown.html('<option value="-1">Loading...</option>').prop("disabled", true);

        // Only load Class options if a valid, non-Others Error is selected
        if (selectedError !== "-1" && selectedError !== "Others") {
            $.ajax({
                type: "POST",
                url: "/Ticket/GetClassCategory",
                // Pass the selected errorCode to the backend
                data: { errorCode: selectedError },
                success: function (data) {
                    let classOptions = '<option value="-1">Please Select Class Type</option>';
                    if (data.length > 0) {
                        data.forEach(classItem => {
                            classOptions += `<option value="${classItem.classCode}">${classItem.classDescription}</option>`;
                        });
                    }
                    classOptions += '<option value="Others">Others</option>';
                    classDropdown.html(classOptions).prop("disabled", false);
                },
                error: () => {
                    classDropdown.html('<option value="-1">Failed to load Class options</option>');
                }
            });
        } else {
            // Reset to disabled state if default or Others is selected
            classDropdown.html('<option value="-1">Select an Error Type first</option>').prop("disabled", true);
        }
    });
});
</script>

Quick Notes:

  • If you need to restrict Class loading to specific Error codes (not just non-Others), you can add a check like if (["ERROR01", "ERROR02"].includes(selectedError)) instead of the current condition.
  • Double-check that your database query in GetClassesByErrorCode correctly filters Class records based on the Error code—this is the backbone of the dependent behavior.

内容的提问来源于stack exchange,提问作者Mrprogrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:00:34