级联下拉列表选择的值

时间:2013-09-17 18:36:00

标签: jquery html asp.net-mvc

我有3个下拉菜单。 1.选择国家2.选择学校3.选择课程。

我有以下代码:

$(function () {
    $("#CountriesID").change(function () {
        $.getJSON("/Account/SchoolList/" + $("#CountriesID").val(), function (data) {
            var items = "<option>Select your school</option>";
            $.each(data, function (i, school) {
                items += "<option value='" + school.Value + "'>" + school.Text + "</option>";
            });
            $("#Schools").html(items);
        });
    });

    $("#Schools").change(function () {
        $.getJSON("/Account/CourseList/" + $("#Schools").val(), function (data) {
            var items = "<option>Select your Course</option>";
            $.each(data, function (i, course) {
                items += "<option value='" + course.Value + "'>" + course.Text + "</option>";
            });
            $("#Courses").html(items);
        });
    });
});

这很好用。 现在,如果有人保存此信息并再次返回其个人资料页面,我需要将保存的值显示为所选选项。

我在Viewbag中保存了schoolid和courseid。 但是如何在上面的代码中使用那个viewbag值作为SELECTED?

2 个答案:

答案 0 :(得分:1)

Demo jsFiddle

这只是一种方法,还有很多。我还建议您发送国家/地区代码,因为您需要填写所有三个下拉列表。

<强> JS

function GetSchools(country) {
    return $.getJSON("/Account/SchoolList/" + country, function (data) {
        var items = "<option>Select your school</option>";
        $.each(data, function (i, school) {
            items += "<option value='" + school.Value + "'>" + school.Text + "</option>";
        });
        $("#Schools").html(items);
    });
}

function GetCourses(school) {
    return $.getJSON("/Account/CourseList/" + , function (data) {
        var items = "<option>Select your Course</option>";
        $.each(data, function (i, course) {
            items += "<option value='" + course.Value + "'>" + course.Text + "</option>";
        });
        $("#Courses").html(items);
    });
}

function OnSuccess(){
    if('@Html.Raw(ViewBag.courseid)' != '')
    {
        $('#Schools').val(@Html.Raw(ViewBag.courseid));
    }
}

$(function () {
    $("#CountriesID").change(function () {
        //Clears the list of Courses since the Country Changed
        $("#Courses").empty();

        //Gets the list of Schools for the new Country
        GetSchools(this.val());
    });

    $("#Schools").change(function () {
        //Gets the list of Courses for the selected school
        GetCourses(this.val());
    });

    if('@Html.Raw(ViewBag.schoolid)' != '')
    {
        $('#Schools').val(@Html.Raw(ViewBag.schoolid));
        $.when(GetCourses('@Html.Raw(ViewBag.schoolid)')).then(OnSuccess);
    }

});

2013年9月17日下午4:29更新

答案 1 :(得分:0)

如果您的代码位于View,则可能会写下以下内容:

$(document).ready(function(){
    var schoolID = "@ViewBag.schoolID";
    var courceID = "@ViewBag.courceID";

    $("#Schools option:selected").val(schoolID);
    $("#Course option:selected").val(courceID);
});

如果您在单独的js文件中使用此代码,则可以使用hiden div来获取ViewBags数据。