如何在选择下拉列表后显示结果

本文关键字:显示 结果 下拉列表 选择 | 更新日期: 2023-09-27 18:33:50

我想在从下拉列表中选择部门后显示课程代码。它从数据库搜索并获取,但不显示在浏览器上。这是下拉菜单:

 <select name="Id" id="Id">
                        <option value="">Select Department</option>
                        @foreach (var departments in ViewBag.ShowDepartments)
                        {
                            <option value="@departments.Id">@departments.Name</option>
                        }
                    </select>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
<script>
    $(document).ready(function() {
        $("#Id").change(function() {
            var departmentId = $("#Id").val();
            var json = { departmentId: departmentId };
            $.ajax({
                type: "POST",
                url: '@Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(json),
                success: function (data) {
                    //$("#myTable").append('<tr><th>ID</th><th>Name</th></tr>');
                    $('#Code').val(data.Code);
                    //$('#ContactNo').val(data.ContactNo);
                    //$('#Type').val(data.Type);
                }
            });
        });
    });
</script>

我正在使用 mvc。

如何在选择下拉列表后显示结果

只要

操作方法返回具有Code属性的 json 结构ViewAllScheduleByDept代码就可以正常工作。

[HttpPost]
public ActionResult ViewAllScheduleByDept(int departmentId)
{  
   //values hardcoded for demo. you may replace it value from db table(s)
   return Json( new { Code="HardcodedValue", ContactNo="12345"} );
}

并且您在页面中有一个输入表单元素,其 Id 属性值为代码

<input type="text" id="Code" />

并且您没有任何阻止JS代码执行的其他脚本错误。

此外,由于您只发送 Id 值,因此实际上不需要使用JSON.stringify方法,也不需要指定contentType属性值。

$("#Id").change(function () {
    $.ajax({
        type: "POST",
        url: '@Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
        data: { departmentId: $("#Id").val() },
        success: function (data) {
            alert(data.Code);
            $('#Code').val(data.Code);
        }
        ,error:function(a, b, c) {
            alert("Error" + c);
        }
    });
});

追加之前使用最后一个

$("#myTable").last().append("<tr><td>ID</td></tr><tr><td>Name</td></tr>");

详情请参阅链接

在 jQuery 中添加表行