在Cascade MVC 3中禁用了DropDownList

时间:2012-07-08 21:19:51

标签: javascript asp.net-mvc-3

我有两个级联的DropDownList

DD2依赖于DD1。

如果D1不包含所选项目的数据,如何禁用DD2?

 $(function () {
         $('#DD1').change(function () {
             var selected1 = $(this).val();
             $.getJSON('@Url.Action("GetCiudadList", "ConsultorioSuper", new { Area = "Superusuario", controller = "Consultorio" })', { IdDD: selected }, function (myData) {
                 var Select2 = $('#DD2');
                 Select2.empty();
                 $.each(myData, function (index, itemData) {
                     citiesSelect.append($('<option/>', {
                         value: itemData.Value,
                         text: itemData.Text
                     }));
                 });
             });
         });

     })

 @Html.DropDownListFor(x => x.SelectedId1, new SelectList(ViewBag.IdUniversidad, "Id1", "Name"), "-- Select --", new { id = "DD1" })
 @Html.DropDownListFor(x => x.SelectedId2, new SelectList(Enumerable.Empty<SelectListItem>(), "Id2", "Name"), "-- Select --", new { id = "DD2" })

祝福

1 个答案:

答案 0 :(得分:1)

  

如果D1不包含所选项目的数据,如何禁用DD2?

您如何知道D1不包含所选项目的数据?在这种情况下,您的控制器操作会返回什么?我想是一个空数组。如果是这种情况,一个简单的if条件就可以完成这项任务:

$.getJSON('@Url.Action("GetCiudadList", "ConsultorioSuper", new { Area = "Superusuario", controller = "Consultorio" })', { IdDD: selected }, function (myData) {
    var Select2 = $('#DD2');
    if (myData.length == null || myData.length == 0) {
        // null or empty data => disable the second ddl and stop executing
        // this function
        Select2.attr('disabled', 'disabled');
        return;
    }

    // at this stage we know that the myData array contains element =>
    // rebind the second dropdown list with those elements
    Select2.empty();
    $.each(myData, function (index, itemData) {
        citiesSelect.append($('<option/>', {
            value: itemData.Value,
            text: itemData.Text
        }));
    });
});