MVC Json Cascade下拉列表

时间:2014-07-10 18:05:12

标签: asp.net ajax json asp.net-mvc-4

我正在尝试发送和接收级联下拉列表的选定值。以下代码适用于将所有信息发送到db,但在重新加载视图时则不然。第一个下拉列表是OK,第二个下拉列表没有那么多 - 它不是“选择”所选值。我希望第二个ddl的视图显示所选的值。谢谢!

    $('#CatDDL').on('change', function () {
    var catName = $('#CatDDL :selected').val();  
    $('#SubCatDDL').empty();
    $.ajax({
        url: "/Product/GetSubCategory",
        type: 'post',
        data: { id: catName },
        dataType: 'json',
        success: function (getSubCategories) {
            var selectedvalue = $('#SubCatDDL :selected').text();
            $.each(getSubCategories, function (i, item) {
                if (item.Value == selectedvalue) {
                    $("#SubCatDDL").append('<option value="' + item.Value + '" selected="true"">' + item.Text + '</option>');
                } else {
                    $("#SubCatDDL").append('<option value="' + item.Value + '">' + item.Text + '</option>');
                }
            })
        }
    })
}).change();

控制器

 public ActionResult GetSubCategory(int id, int? selectedValue)
    {
        EFDbContext dbc = new EFDbContext();

        var getSubCategory = from ...
            select new SelectListItem { Text = SubCatName, Value = SubCatID };
        return Json(new SelectList(getSubCategory, "Value", "Text", selectedValue));
    }

查看

@Html.DropDownList("SubCatID", new SelectList(string.Empty, "Value", "Text", "Select A SubCategory"), new { @class = "form-control", id = "SubCatDDL", name = "SubCatDDL" })

0 个答案:

没有答案