List Dropdownlist dependent or Married - Visual.Net -MVC

0

I would like to know how to use dependent Dropdownlist, for example that the CITY depends on the REGION, and that of the COUNTRY.

I am currently using this way of working when listing a dropdownlist:

In the controller;      Function Update Members () As ActionResult         ViewBag.Cargoslist = GetCharges (Nothing)      End Function

 Private Function GetCargos(selectedValues As String()) As MultiSelectList
    Using db As New BD_LOSCOPIHUESEntities1
        Dim cargos = db.CARGO.Select(Function(x) New With { _
                                         .IdCargo = x.IdCargo, _
                                         .NombreCargo = x.NombreCargo}).ToList()
        ViewBag.ListadoCargo = New MultiSelectList(cargos, "IdCargo", "NombreCargo")

        Return New MultiSelectList(cargos, "IdCargo", "NombreCargo", selectedValues)
    End Using
End Function

In the view I use webform, which is almost the same as razor:

<%:Html.DropDownList("region", TryCast(ViewBag.Regioneslist, MultiSelectList), "Seleccione...", New With {Key .[class] = "form-control estilo_dropdownlist input-sm"})%> 

Currently I have seen examples in C #, but when I transfer it to visual, it does not work for me. I would like how I could do dependent dropdownlist.

    
asked by Danilo 12.07.2016 в 03:14
source

2 answers

0

I found a good solution, in the Controller:

Public Function Index() As ActionResult
    ViewData("titulo") = "cascada de prueba"
    Using db As New BD_LOSCOPIHUESEntities1
        Dim regiones = db.REGION.Select(Function(x) New With { _
                                         .Value = x.IdRegion, _
                                         .Text = x.Nombre}).ToList()

        Dim model As New DropDownListCascadeViewModel()
        model.regiones = New SelectList(regiones, "Value", "Text")
        model.ciudades = New SelectList(New List(Of SelectListItem)(), "Value", "Text")

        Return View(model)
    End Using
End Function


  <HttpPost> _
  Public Function GetCiudades(typeCiudad As String) As JsonResult
    Dim type As Integer = Integer.Parse(typeCiudad)
    Dim list As New List(Of SelectListItem)()

    Using db As New BD_LOSCOPIHUESEntities1
        Dim ciudadesSelect = db.CIUDAD.Where(Function(y) y.IdRegion = type).Select(Function(x) New With { _
                                         .Value = x.IdCiudad, _
                                         .Text = x.Nombre}).ToList()         

        Dim model As New DropDownListCascadeViewModel()
        model.ciudades = New SelectList(ciudadesSelect, "Value", "Text")

        Return Json(New With {model.ciudades})
    End Using
End Function

I created a class of type ViewModel (it's the way I call it):

Public Class DropDownListCascadeViewModel
Public Property selectedRegion() As Integer
    Get
        Return m_selectedRegion
    End Get
    Set(value As Integer)
        m_selectedRegion = value
    End Set
End Property
Private m_selectedRegion As Integer
Public Property selectedCiudades() As Integer
    Get
        Return m_selectedCiudades
    End Get
    Set(value As Integer)
        m_selectedCiudades = value
    End Set
End Property
Private m_selectedCiudades As Integer

Public regiones As System.Web.Mvc.SelectList
Public ciudades As System.Web.Mvc.SelectList
End Class

and in the view, at the beginning reference to the ViewModel that I made:

<%@ Page Language="VB" Inherits="System.Web.Mvc.ViewPage(Of IMPCHLosCopihues_MVC.DropDownListCascadeViewModel)" %>

Through Jquery with AJAX in Vista:

<script type="text/javascript" src="../../Scripts/jquery-1.11.3.min.js">           </script>
  <script type="text/javascript">

    $(function () {
        $('#selectedRegion').change(function () {
            var typeCiudad = $('#selectedRegion :selected').val();
            typeCiudad = typeCiudad == "" ? 0 : typeCiudad;
            //When select 'optionLabel' we need to reset it to default as well. So not need 
            //travel back to server.
            if (typeCiudad == "") {
                $('#selectedCiudades').empty();
                $('#selectedCiudades').append('<option value="">--Select a language--</option>');
                return;
            }

            //This is where the dropdownlist cascading main function
            $.ajax({
                type: "POST",
                url: "GetCiudades",                            //Your Action name in the DropDownListConstroller.cs
                data: "{'typeCiudad':" + typeCiudad + "}",  //Parameter in this function, Is cast sensitive and also type must be string
                contentType: "application/json; charset=utf-8",
                dataType: "json"

            }).done(function (data) {
                //When succeeded get data from server construct the dropdownlist here.
                if (data != null) {

                    $('#selectedCiudades').empty();
                    $.each(data.ciudades, function (index, data) {
                        $('#selectedCiudades').append('<option value="' + data.Value + '">' + data.Text + '</option>');
                    });
                }
            }).fail(function (response) {
                if (response.status != 0) {
                    alert(response.status + " " + response.statusText);
                }
            });
        });
    });

<body>
Region<%: Html.DropDownListFor(Function(m) m.selectedRegion, Model.regiones, "--Seleccione la Region--")%>
<br />
Ciudad <%:Html.DropDownListFor(Function(m) m.selectedCiudades, Model.ciudades, "--Seleccione la Ciudad--")%>
<br />
</body>

And so I can have Dropdownlist dependent.

Is the issue like loading the data stored in the Dropdownlist, to make the Update?

    
answered by 14.07.2016 / 01:19
source
2

There are several ways to achieve combos in dependents

1-An option could be using jquery , by means of $.ajax() or $.getJSON() you can invoke the action of the controller that will return in response json used to load the items of the next combo

Cascading DropDownList in ASP.Net MVC

Creating Simple Cascading DropDownList In MVC 4 Using Razor

The idea is that you define two dropdownlist but to the first one you attach the jquery change event, then when you change the option it will throw the event in the client, it is there when using the $ .ajax to invoke an action in the controller to return the list in json to create the options of the second combo

2- Through helper @Html.CascadingDropDownListFor()

CascadeDropDown Helpers

You will notice that it allows to define in the view how it relates to the first combo

3- Using @Ajax.BeginForm()

Simple Implementation of MVC Cascading Ajax Drop Down

Applying ajax by means of a submit to the controller created by the Ajax.BeginForm (), you can update a section of the view to inject in this the html of the second combo that will show the options depending on the selection of the first combo

    
answered by 12.07.2016 в 06:55