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

时间:2016-02-09 18:20:27

标签: c# jquery json asp.net-mvc-5 cascadingdropdown

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



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

<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。

2 个答案:

答案 0 :(得分:2)

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

[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);
        }
    });

});

答案 1 :(得分:0)

在追加

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

请参阅链接了解详情

Add table row in jQuery