How to create a Cascading DropDown?

2

I would like to create a DropDown dependent on another DropDown in C #, ASP.NET - MVC 5, in that case it would be a dropDown with the names of all the client and then another DropDown with the Client's phones selected in the first DropDown. How to do?

Class: Order

 public class Pedido
{
    public Pedido()
    {
        this.Produtos = new List<Produto>();
    }      

    [Key]
    public int PedidoID { get; set; }

    public Cliente Cliente { get; set; }

    [Display(Name = "Nome do Cliente")]
    public int ClienteID { get; set; }

    [Display(Name = "Telefone")]
    public string ClienteFone { get; set; }

    [Display(Name = "Cidade")]  
    public string   ClienteCidade { get; set; }

    [Display(Name = "Estado")]
    public string ClienteEstado { get; set; }

    [Display(Name = "Endereço")]
    public string ClienteEndereço { get; set; }

    public ICollection<Produto> Produtos { get; set; }

    [Display(Name = "Status to pedido")]
    public Estatus Estatus { get; set; }

    public int EstatusID { get; set; }

    [Display (Name="Data do pedido")]
    public DateTime DataPedido { get; set; }

}

Create.cshtml

 @Html.ValidationSummary(true)
    <div class="form-group">
        @Html.LabelFor(model => model.ClienteID, "ClienteID", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("ClienteID", String.Empty)
            @Html.ValidationMessageFor(model => model.ClienteID)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ClienteFone, "ClienteFone", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("ClienteFone", String.Empty)
           @* @Html.EditorFor(model => model.ClienteFone)*@
            @Html.ValidationMessageFor(model => model.ClienteFone)
        </div>
    </div>
    
asked by anonymous 27.11.2014 / 01:24

1 answer

3

Do as follows, below is an example with a table with the following structure

clientes(ClienteID, Nome, Telefone)

Controller

var clientes = (select u in model.clientes ......).ToList();

ViewBag.Clientes = new SelectList(clientes, "ClienteID", "Nome");
ViewBag.Telefones = new SelectList(clientes, "telefone", "telefone");

View

@Html.DropDownListFor(model => model.ClienteID, (SelectList)ViewBag.Clientes) /* Gera um select com nomes e value o ClienteID */

@Html.DropDownListFor(model => model.ClienteFone, (SelectList)ViewBag.Telefones) /* Gera um select com telefones e value o telefone */

I hope you have understood the usage, validation continues the same thing, the fields and the list in the controller you change to the list of clients of your system.

Now to populate the second DropDownList by selecting based on the first, you will need to use javascript

View

@Html.DropDownListFor(model => model.ClienteID, (SelectList)ViewBag.Clientes, new {id="clienteID"}) /* Gera um select com nomes e value o ClienteID */

@Html.DropDownListFor(model => model.ClienteFone, String.Empty, new {id="clienteFone"})

Controller

public JsonResult ListaTelefones(int clienteID) {
   var telefones = (from u in model.telefones where u.ClienteID select u.telefone).toList(); //Nesse caso estou usando uma tabela ficticia com os telefones do cliente cadastrado

   return Json(telefones, JsonRequestBehavior.AllowGet);
}

Jquery

$('#clienteID').change(function() {
   var clienteID = $(this).val();

   $.get('/MeuController/ListaTelefones', {clienteID : clienteID}).done(function(data){
      var drop = $('#clienteFones');
      drop.html("");
      $.each(data, function(i, item) {
         drop.append('<option val="'+item+'">'+item+'</option>');
      });
   });
});
    
27.11.2014 / 20:47