How to create a Cascading Dropdown?

Asked

Viewed 1,119 times

2

I would like to create a Dropdown dependent on another Dropdown in C#, ASP.net - MVC 5, in case it would be a dropdown with the names of all customers and then another Dropdown with the phones of the Customer selected in the first Dropdown. How to do?

Class : Request

 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>

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 use, the validation remains the same thing, the fields and the list in the controller you change to the client list of your system.

Now to popular the second DropDownList by selecting based on the first, it will be necessary 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>');
      });
   });
});
  • I’m having trouble putting the id’s in the dropdowns, that’s how it is?

  • What kind of problem?

  • I am not receiving the value of the second dropdown to register in the bank, when I select the client I view the phones but it is not running by the Create method in my controller

  • This is because of the "bind" that MVC makes with the data, forget creating with Razor and do <select id="clienteFone" name="clienteFone"></select> Probably now it should pass.

Browser other questions tagged

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