且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据从另一个DropDownList中选择的值填充一个DropDownList

更新时间:2022-05-09 22:22:46

您可以将第一个 select 的选定值传递给服务器端,查询数据库并将结果成功返回给客户端.Ajax的回调函数以填充第二个 select .以下代码供您参考:

You can pass selected value of the first select to server side , query the database and return result back to client side , in success callback function of ajax to fill the second select . Code below is for your reference :

$("#SelectedType").on("change", function () {                
    $.ajax({
        type: 'GET',
        url: "/home/GetTypesBasedOnValueFromOtherDropDownList",
        contentType: 'application/json',
        data: { Type: $("#SelectedType").val() },
        success: function (data) {
            var s = '<option value="-1">Please Select a Course</option>';
            for (var i = 0; i < data.length; i++) {
                s += '<option value="' + data[i].courseCode + '">' + data[i].courseName + '</option>';
            }
            $("#secondSelect").html(s);  
        }
    });
})

服务器端:

public IActionResult GetTypesBasedOnValueFromOtherDropDownList(string Type)
{
    //you can query database instead 
    List<AdmInstCourses> admInstCourses = new List<AdmInstCourses>();
    admInstCourses.Add(new AdmInstCourses() { CourseCode = 1, CourseName = "name1", Units = "3.2" });
    admInstCourses.Add(new AdmInstCourses() { CourseCode = 2, CourseName = "name2", Units = "3.3" });

    return new JsonResult(admInstCourses);
}