0

I have the next on my View:

                <select id="AreaSelect" class="custom-select" name="AreaClave">
                    @if (ViewBag.areasSelect != null)
                    {
                        <option value="NA" selected>ALL</option>
                        foreach (AreasCert areasItem in (List<AreasCert>)ViewBag.areasSelect)
                        {
                            <option value="@areasItem.AreaClave">@areasItem.AreaClave</option>
                        }
                    }
                </select>

And I have an Action that returns multiple ViewBags and a Model with information:

        public ActionResult EmpOperaciones(CertsxOpxAreas certsxOpxAreas)
        {
            GetOpFromEmpleado(certsxOpxAreas);
            certsxOpxAreas.EmpidCoordinador = GetOpFromEmpleado(certsxOpxAreas)[1].EmpidCoordinador;

            ViewBag.areasSelect = AreaSelect();
            return View(certsxOpxAreas);
        }

        public List<AreasCert> AreaSelect()
        {
            SqlConnection con = (SqlConnection)_contextFRTFGRAL.Database.GetDbConnection();
            SqlCommand cmd = con.CreateCommand();
            List<AreasCert> areasSelect = new();

            // Realizamos una query para obtener todas las descripciones de las operaciones.
            con.Open();
            cmd.CommandText = "SELECT areaClave FROM cert.areasCerts " +
                "WHERE Activa = 1 " +
                "ORDER by areaClave ASC";
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    areasSelect.Add(new AreasCert
                    {
                        AreaClave = reader["areaClave"].ToString()
                    });
                }
            }
            con.Close();
            return areasSelect;
        }

I want to create another select menu with options based on the selection of the user (i.e. display the operations in area1 when user selects that) My first approach was to have something like this:

function AreasSelect() {
    d = document.getElementById("AreaSelect").value;
    window.location.href = "?Area=" + d;
}

And have an onchange function on the select item, but I don't think this is an efficient way to achieve this, is there a way to do this as clean as posible?

Miguel V
  • 606
  • 2
  • 6
  • 18
  • If I understand correctly you should look at this QA https://stackoverflow.com/questions/22955839/how-to-fill-a-dropdown-using-jquery-ajax-call it explains how to fill a dropdownlist calling a c# method in a aspx.cs using jquery or this one more focused on MVC: https://stackoverflow.com/questions/14339089/populating-dropdown-with-json-result-cascading-dropdown-using-mvc3-jquery-aj – Steve Sep 02 '21 at 21:13

1 Answers1

1

You can use ajax to get second DropDown value,and then set html of second DropDown.Here is a working demo:

Actions

[HttpGet]
        public ActionResult EmpOperaciones()
        {
            ViewBag.areasSelect = AreaSelect();
            return View();
        }
        [HttpPost]
        public JsonResult EmpOperaciones(string Area)
        {
            
            return new JsonResult(new List<SelectListItem> { new SelectListItem {  Text="option1_"+Area,Value="option1"}, new SelectListItem { Text = "option2_" + Area, Value = "option2" }, new SelectListItem { Text = "option3_" + Area, Value = "option3" } });
        }

        public List<AreasCert> AreaSelect()
        {
            List<AreasCert> areasSelect = new List<AreasCert> { new AreasCert { AreaClave = "AreaClave1" }, new AreasCert { AreaClave = "AreaClave2" }, new AreasCert { AreaClave = "AreaClave3" } };

            
            return areasSelect;
        }

View:

<select id="AreaSelect" class="custom-select" name="AreaClave" onchange="AreasSelect(this)">
    @if (ViewBag.areasSelect != null)
    {
        <option value="NA" selected>ALL</option>
        foreach (AreasCert areasItem in (List<AreasCert>)ViewBag.areasSelect)
        {
            <option value="@areasItem.AreaClave">@areasItem.AreaClave</option>
        }
    }
</select>
<select class="form-control" id="SecondDropDown" name="SecondDropDown">
    <option value="NA" selected>ALL</option>
</select>
@section scripts
{
    <script>
        function AreasSelect(t) {
            $.ajax({
                type: "POST",
                url: "",
                data: { "Area": $(t).val() },
                dataType:"json",
                success: function (data) {
                    var items = "<option value='NA'>ALL</option>";
                    $("#SecondDropDown").empty();
                    $.each(data, function (index, data) {
                        items += "<option value='" + data.value + "'>" + data.text + "</option>";
                    });
                    $('#SecondDropDown').html(items);
                },
                failure: function () {
                    alert("Failed!");
                }
            });
        }
    </script>


} 

result: enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22