locked
dropdownlist cascading - when i select the first item of dropdown he don't load the second - (sorry, i'm brazilian and i don't speak english very well rsrs) RRS feed

  • Question

  • User-1811068489 posted
    Guys, good night !!! I am a total newbie to ASP.NET and would like your help. Choose an example on the internet from a cascading dropdownlist.
    However, when implemented in my application it will not work as it should.
    It loads the first dropdownlist, but when I select a value, it doesn't load the second dropdownlist.
    Don't give me an error, so don't load.
    The example I took was using:
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    I changed to (because this is version that i'm using):
    <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>
    Thank you if you can help me!!! 
    Friday, April 17, 2020 11:48 PM

All replies

  • User-1330468790 posted

    Hi frlopes,

      

    The problem is located in the javascript function that you have a syntax error in below code.

    $(function () {
                if ($("#projetoId").val() != "" && $("#moduloId").val() != "" {
                    var message = "Projeto: " + $("#projetoId option:selected").text();
                    message += "\nModulo: " + $("#moduloId option:selected").text();
                    alert(message);
                }
            });

    You should embrace the if condition in parentheses "()" however you miss a right one.

    Modify the code as below:

    $(function () {
                if ($("#projetoId").val() != "" && $("#moduloId").val() != ""){
                    var message = "Projeto: " + $("#projetoId option:selected").text();
                    message += "\nModulo: " + $("#moduloId option:selected").text();
                    alert(message);
                }
            });

     

    Before doing the correction, you could check if there is any error message inside the debugger of the browser. (Press F12 and click "Console" tab).

     

    Hope this can help you.

    Best regards,

    Sean

    Saturday, April 18, 2020 5:53 AM
  • User-1811068489 posted
    Sean, thank you very much for your help! 
     
    After the change, the second dropdown was loaded, however, now, when I click the "submit" button the idts, they are empty.
    Could you help me again? Pleeeease!!! <3
    $("#projetoId").val() && $("#moduloId").val() are empty
    :-(
    I have more 2 models in the project:
    I don't know if there is anything related to the problem
    public class Projeto
        {
            [Key]
            public int projetoId { get; set; }
    
            [Display(Name = "Descrição")]
            public string descricao { get; set; }
    
            [Display(Name = "Sigla")]
            public string sigla { get; set; }
    
            [Display(Name = "Status")]
            public Ativo ativo { get; set; }
    
            [Display(Name = "Dt. Criação")]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
            public DateTime? dataCriacao { get; set; }
        }
      public class Modulo
        {
            [Key]
            public int moduloId { get; set; }
    
            [Display(Name = "Descrição")]
            public string descricao { get; set; }
    
            [Display(Name = "Status")]
            public Ativo ativo { get; set; }
    
            [Display(Name = "Dt. Criação")]
            public DateTime? dataCriacao { get; set; }
    
            [Display(Name = "Projeto")]
            public Projeto Projeto { get; set; }
            public Modulo()
            {
                Projeto = new Projeto();
            }
        }
    I took this example and adapted it to my needs:

    Best Regards,
    Fabiola
    =)
    Sunday, April 19, 2020 2:39 AM
  • User-1330468790 posted

    Hi frlopes,

      

    I tried the code and it should be working.

    When I sumbit the form with filling the select list with values, the page will be reloaded and give me an alert with the selected values.

    You can see the demo from my side:

      

    The only problem I can see is that when you submit the page without choosing both of values and you will get a server error.

    Is this your problem?

    If not, have you changed the code? I mean anything related to the CascadingModel and database.

    Could you please provide me with the schema of the database? It would be better to show me all of the data.

     

    Best regards,

    Sean

    Sunday, April 19, 2020 7:36 AM
  • User-1811068489 posted

    Hi Sean, 

    I choose both of values and submit the page, and then, don't return the values (moduloId, projetoId).

    It does not give the alert because it does not enter the if 

    if ($("#projetoId").val() != "" && $("#moduloId").val() != "")

    In this link is my project and database, if you can look, thank you again.

    https://mega.nz/folder/rxsnyZZB#hLWlxrpP9QepQo3wGj2eHA

    Thank you very much

    Sunday, April 19, 2020 3:53 PM
  • User-1811068489 posted

    Hi, Sean,</div> <div></div> <div>I found the error, because of the code below in Global.asa</div> <div>if I comment, it's ok, but I don't know why and I don't know how to fix.</div> <div>

    ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
    ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());
    ModelBinders.Binders.Add(typeof(int), new Int32ModelBinder());
    ModelBinders.Binders.Add(typeof(int?), new Int32ModelBinder());
    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

    </div> <div>However, I modified my project again to call the page "dropdownlist cascading" from a menu after login and started giving the following error in the image attached at the link, when I select a value from the first dropdownlist</div> <div> </div> <div>I will post my project if you can help me.</div> <div> </div> <div>-- user to login cpf: 11111111111</div> <div>-- password: fabiola</div> <div>-- Then, click "Gerencial", "Projeto x Modulo"</div> <div></div> <div>https://mega.nz/folder/m9EUUKSK#Gh8tSAln4IiRIulXyDkKCw</div> <div></div> <div></div> <div>Thanks!!!</div>

    Sunday, April 19, 2020 11:28 PM
  • User-1330468790 posted

    Hi frlopes,

     

    Glad to hear that you found where the problem was.

    I suggest you post above new problem in a new thread so that the members could focus on a single problem, which will make the problem solving much easier.

     

    About this thread, if you find the answer is helpful, I suggest you could mark the answer. This will help other people who faces the same issue to find the right answer faster.

     

    Best regards,

    Sean

    Monday, April 20, 2020 1:49 AM