Fill cascading combos in MVC

1

In a view I have 4 combos. The first 3 I fill them without problems with data of tables of a BD. But the 4th one I need to fill it with information from another table, which I should filter depending on the selected in the 3 previous combos.

Example:

Combo 1: Types of service. Combo 2: Branches. Combo 3: Date. Combo 4: all the records of the timetable that have service type, branch and date equal to those selected in the previous combos.

I found several examples but all of them explain how to fill one combo from another. In my case I must fill it out from other 3.

How can I do this? Is it necessary to use javascrippt?

EDIT:

I managed to do it this way:

View:

<script type="text/javascript">
        $(document).ready(function () {
            $("#Servicios").change(function () {
                $("#Horarios").empty();
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("ObtenerHorarios")',
                    dataType: 'json',
                    data: { servicio: $("#Servicios").val(), sucursal: $("#Sucursales").val() },

                    success: function (turnos) {
                        $.each(turnos, function (i, turno) {
                        $("#Horarios").append('<option value="' + turno.Id + '">' +
                                turno.Horario + '</option>');
                        });
                    },

                    error: function (ex) {
                        alert('Error al obtener los horarios disponibles' + ex);
                    }
                });
                return false;
            })
        });
    </script>

Controller:

public JsonResult ObtenerHorarios(int servicio, int sucursal)
    {
        return Json(
            new SelectList(
                // Aquí obtengo la lista de items y la filtro según los parámetros pasados
                // desde la vista a través de ajax
                items: _turServicio.ObtenerTurnosDisponibles()
                           .Where(t => t.IdServicio == servicio && t.IdSucursal == sucursal)
                           .Select(t => new SelectListItem { Text = t.Horario, Value = t.Id.ToString() }),
                dataValueField: "Value",
                dataTextField: "Text"
            )
        );
    }

But I have one small detail to solve: the whole process is working because depending on the options chosen in the combos above, it shows me the number of corresponding options in the destination combo, but the problem is that they do not come out with the name of property but they come out as "undefinied".

Any suggestions?

EDIT AGAIN - RESOLVED!

In the function js instead of putting turn.Id and turn.Horario, I have to put shift.Value and turn.Text, because those are the identifiers of values and texts of the list that happened to you in format json from the controller.

    
asked by Willy616 17.05.2017 в 15:27
source

1 answer

1

According to me, you can only achieve it with javascript. Basically it's about acquiring the value of your dropdowns and passing them to your method in the controller.

Here is a solution with jquery and an ajax call.

The controller

    public ActionResult Index()
    {
        var flavorItems = new List<SelectListItem>() {
            new SelectListItem() { Value = "1", Text = "Chocolate" },
            new SelectListItem() { Value = "2", Text = "Double Chocolate" },
            new SelectListItem() { Value = "3", Text = "Chocolate Chip" },
            new SelectListItem() { Value = "4", Text = "Peanut Butter & Chocolate" },
        };

        ViewBag.FlavorItems = flavorItems;

        return View();
    }

    public ActionResult Update_DropDownList(int a, int b, int c)
    {
        // Use your parameters values to create your new list
        return Json(new[] {
            new { Id = 1, Name = "Vanilla" },
            new { Id = 2, Name = "Strawberry" },
            new { Id = 3, Name = "Mint" },
        }, JsonRequestBehavior.AllowGet);
    }

The view (with javascript)

<p>@Html.DropDownList("SelectedFlavorId1", ViewBag.FlavorItems as List<SelectListItem>, htmlAttributes: new { @class = "form-control ddl" })</p>
<p>@Html.DropDownList("SelectedFlavorId2", ViewBag.FlavorItems as List<SelectListItem>, htmlAttributes: new { @class = "form-control ddl" })</p>
<p>@Html.DropDownList("SelectedFlavorId3", ViewBag.FlavorItems as List<SelectListItem>, htmlAttributes: new { @class = "form-control ddl" })</p>
<p>@Html.DropDownList("SelectedFlavorId4", new List<SelectListItem>(), htmlAttributes: new { @class = "form-control" })</p>

@section Scripts {
<script>
    $(".ddl").on('change', function () {
        var a = $("#SelectedFlavorId1").val();
        var b = $("#SelectedFlavorId2").val();
        var c = $("#SelectedFlavorId3").val();
        $.getJSON('/home/Update_DropDownList', {a: a, b: b, c: c }, function (result) {
            var ddl = $('#SelectedFlavorId4');
            ddl.empty();
            $(result).each(function () {
                $(document.createElement('option'))
                    .attr('value', this.Id)
                    .text(this.Name)
                    .appendTo(ddl);
            });
        });
    });
</script>
}
    
answered by 17.05.2017 в 22:17