Dropdownlist Scading - Does not load the second dropdownlist

Asked

Viewed 22 times

-1

good night!!!

I’m a total newbie on this Asp.net and I’d like some help from you guys.

I got an example on the Internet of a waterfall dropdownlist. However, when I implemented it in my application it did not work as it should. It loads the first dropdownlist, but when I select a value, it does not load the second dropdownlist. It does not return an error, it just does not load.

The example I took was using:

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

And mine, I switched to

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

Which is the jquery version I’m using.

I really appreciate it if someone can help me!!!

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>

1 answer

0

Not to mention the security issues you’re presenting while mounting your queries this way...

See that your Action AjaxMethod does not expect to receive a Json object... Asp.net and MVC help you serialize and deserialize the objects... but you need to reflect its structure.

Create a Viewmodel or DTO for this:

public class AjaxMethodViewModel
{
   public string Type {get; set;} 
   public int Value {get; set;}
}

Change the arguments of your action to that object that was declared above:

[HttpPost]
public JsonResult AjaxMethod([FromBody]AjaxMethosViewModel request)
{
    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);
}

But most importantly, beginner or experienced, you need to understand what you’re doing. Don’t use a code you found on the internet without understanding what’s going on line-by-line. And a good way to improve this is by debugging...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.