Dropdownlist cascata - não carrega o segundo dropdown

17/04/2020

0

Pessoal, boa noite!!!

Sou novata total nesse asp.net e gostaria de uma ajuda de vocês.

Peguei um exemplo na internet de um dropdownlist em cascata.
Porém, quando implementei na minha aplicação ele não funcionou como deveria.
Ele carrega o primeiro dropdownlist, porém quando eu seleciono um valor, ele não carrega o segundo dropdownlist. Não me retorna erro, só não carrega.

O exemplo que peguei estava utilizando:

<script src="~/Scripts/jquery-1.10.2.min.js"></script>


E o meu, alterei para: (que é a versão que estou usando)

<script src="~/Scripts/jquery-3.3.1.min.js"></script>


Model:

public CascadingModel()
        {
            this.Projeto = new List<SelectListItem>();
            this.Modulo = new List<SelectListItem>();
        }

        public List<SelectListItem> Projeto { get; set; }
        public List<SelectListItem> Modulo { get; set; }

        public int projetoId { get; set; }
        public int moduloId { get; set; }


Controller:

public ActionResult Index()
        {
            CascadingModel model = new CascadingModel();
            model.Projeto = PopulateDropDown("SELECT projetoId, descricao FROM projeto", "descricao", "projetoId");
            return View(model);
        }

        [HttpPost]
        public JsonResult AjaxMethod(string type, int value)
        {
            CascadingModel model = new CascadingModel();
            switch (type)
            {
                case "projetoId":
                    model.Modulo = PopulateDropDown("SELECT moduloId, descricao FROM modulo WHERE projetoId = " + value, "descricao", "moduloId");
                    break;
            }
            return Json(model);
        }

        [HttpPost]
        public ActionResult Index(int projetoId, int moduloId)
        {
            CascadingModel model = new CascadingModel();
            model.Projeto = PopulateDropDown("SELECT projetoId, descricao FROM projeto", "descricao", "projetoId");
            model.Modulo = PopulateDropDown("SELECT moduloId, descricao FROM modulo WHERE projetoId = " + projetoId, "descricao", "moduloId");
            return View(model);
        }

        private static List<SelectListItem> PopulateDropDown(string query, string textColumn, string valueColumn)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            string constr = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            items.Add(new SelectListItem
                            {
                                Text = sdr[textColumn].ToString(),
                                Value = sdr[valueColumn].ToString()
                            });
                        }
                    }
                    con.Close();
                }
            }

            return items;
        }


Index:

<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.DropDownListFor(m => m.projetoId, Model.Projeto, "Please select")
        <br />
        <br />
        @Html.DropDownListFor(m => m.moduloId, Model.Modulo, "Please select")
        <br />
        <br />
      
        <input type="submit" value="Submit" />
    }
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("select").each(function () {
                if ($(this).find("option").length <= 1) {
                    $(this).attr("disabled", "disabled");
                }
            });

            $("select").change(function () {
                var value = 0;
                if ($(this).val() != "") {
                    value = $(this).val();
                }
                var id = $(this).attr("id");
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: '{type: "' + id + '", value: ' + value + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var dropDownId;
                        var list;
                        switch (id) {
                            case "projetoId":
                                list = response.Modulo;
                                DisableDropDown("#moduloId");
                                PopulateDropDown("#moduloId", list);
                                break;
                        }
                        
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });

        function DisableDropDown(dropDownId) {
            $(dropDownId).attr("disabled", "disabled");
            $(dropDownId).empty().append('<option selected="selected" value="0">Please select</option>');
        }

        function PopulateDropDown(dropDownId, list) {
            if (list != null && list.length > 0) {
                $(dropDownId).removeAttr("disabled");
                $.each(list, function () {
                    $(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        }

        $(function () {
            if ($("#projetoId").val() != "" && $("#moduloId").val() != "" {
                var message = "Projeto: " + $("#projetoId option:selected").text();
                message += "\nModulo: " + $("#moduloId option:selected").text();
                alert(message);
            }
        });
    </script>
</body>
Fabíola Lopes

Fabíola Lopes

Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar