How popular a Dropdownlist from another Dropdownlist

Asked

Viewed 7,119 times

8

I need to know how to popular a Dropdownlist from another Dropdownlist. Example: I have a Dropdownlist called Project that takes information from my DB. When I select for example "Project 1" I need to load in my second Dropdownlist all Sub Projects belonging to "Project 1". All this information is on DB. I’m not getting popular the second Dropdown. I saw that can be done via Javascript/Json, but I have no idea how to do it. I need help.

Here I populate my first dropdown

 public ActionResult CadastrarAtividades()
    {
        //Lista que recebe todos os PROJETOS ja cadastrados no banco
        List<Projeto> projetos = new ProjetoNegocio().Get();
        ViewBag.ListaProjeto = new SelectList(projetos.Where(x => x.ProjetoIdPai == null), "ProjetoId", "Nome");

        ViewBag.ListaProjetos2 = projetos;

Here I populate my second dropdown. But here I need the data to be according to what was selected in the first dropdown.

//Lista que recebe todos os SUBPROJETOS ja cadastrados no banco
        List<Projeto> subprojetos = new ProjetoNegocio().Get();
        ViewBag.ListaSubProjeto = new SelectList(subprojetos.Where(x => x.ProjetoIdPai != null), "ProjetoId", "Nome");

View

<div class="panel-body">
                <div class="col-lg-10">
                    @using (Html.BeginForm("CadastrarAtividades", "Apontamento", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {
                        @Html.AntiForgeryToken()
                        <br /><br />
                        <table class="table table-bordered table-hover">
                            <div class="form-group">
                                @Html.Label("Projeto")
                                <div>
                                    @Html.DropDownListFor(model => model.ProjetoId, new SelectList(ViewBag.ListaProjeto, "Value", "Text"), "Selecione", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(m => m.ProjetoId, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group">
                                @Html.Label("Sub Projeto")
                                <div>
                                    @Html.DropDownListFor(model => model.ProjetoId, new SelectList(ViewBag.ListaSubProjeto, "Value", "Text"), "Selecione", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(m => m.ProjetoId, "", new { @class = "text-danger" })
                                </div>
                            </div>
  • Did I not understand, because the second dropdown is popular from the first if the information from the second will refer to a different project from the first? Or the information of the second dropdown will be identical to the first?

  • So the information comes from the same DB table. What differentiates one from the other is if the Project has an "Idprojetopai" it is a Sub Project, if it does not have an "Idprojetopai" it is a Project.

  • @Raphaelgumm post what ever tried, will help us help you.

  • As Marconi said, it would be better to explain your situation better: the data coming from DB are with this subproject filter? Did you manage to connect to DB and pull the dice and play in a variable? Or was this data loaded on the first call? The call to DB ta being made as? By MVC? Or have an AJAX call? Try to explain your problem better, if possible maybe a little code, because there are many options to solve your problem.

  • I edited the question. @Johnnybigoode I’m not doing via Javascript.

2 answers

9


For this answer, I will assume that your project has installed jQuery and JSON.NET (both come by default in an ASP.NET MVC project).

First, isolate the search for a subproject in a Action to return a JSON:

    public async Task<JsonResult> SelecionarPorProjeto(int id)
    {
        // Tomei uma liberdade poética aqui. Não sei se Get aceita
        // parâmetros, mas a título de exemplo, vamos supor que sim.
        var subprojetos = new ProjetoNegocio().Get(id);
        return Json(subprojetos.Where(x => x.ProjetoIdPai != null).ToList(), JsonRequestBehavior.AllowGet);
    }

Then open a @section Scripts in his View and put a code that triggers an Ajax request when the DropDown of projects is amended:

@section Scripts 
{
    <script>
        $("#ProjetoId").change(function () {
            $.ajax({
                url: "/Subprojetos/SelecionarPorProjeto/" + id,
                success: function (data) {
                    $("#SubprojetoId").empty();
                    $("#SubprojetoId").append('<option value>Selecione...</option>');
                    $.each(data, function (index, element) {
                        $("#SubprojetoId").append('<option value="' + element.ProjetoId + '">' + element.Text + '</option>');
                    });
                }
            });
        });
    </script>
}

This should be enough to fix.

6

I believe you’re referring to a Cascade Dropdownlist. Where you select an object in the first and use the value as a parameter to fill the second. Very common in registers using Country/State/City.

The way I usually do is to populate the first DropDownList and use the value of the option selected as a search parameter in a Action. That one Action gives me a list of the data, in JSON.

To do this way, first you create in your controller a method to return the desired list, this way:

public JsonResult ObterProjetos(int projetoId)
        {
            var projetos = new ProjetoNegocio().Get();//Método para obter os projetos aqui
           //Retorna o valor em JSON
            return Json(projetos, JsonRequestBehavior.AllowGet);
        }

After that, you use this script to call his Action based on the selected value.

<script type="text/javascript">
    $(document).ready(function () {
        //Coloque aqui o id do primeiro dropdownlist
        $('#ProjetoId').change(function () {
            //obtém o valor selecionado
            var id = $(this).find(":selected").val();
            //Chama a Action para popular o segundo DropDownList
            $.getJSON('/Projeto/ObterSubProjetos', { projetoId: id }, function (data) {
                //Remove os dados que já possui
               //Aqui entra o ID do segundo DropDownList
                $('#ProjetoIdNovo option').remove();
                $('#ProjetoIdNovo').append('<option value="">Selecione uma Cidade</option>');
                //Popula os options com os valores retornados em JSON
                for (var i = 0; i < data.length; i++) {
                    $('#ProjetoIdNovo').append('<option value="' +
                        data[i].ProjetoId + '"> ' +
                        data[i].NomeProjeto + '</option>');
                }
            });
        });
    });
</script>

The above code is responsible for "picking up" the value selected in the first DropDownList, use it as a parameter for your controller and fill the second Dropdownlist according to the list returned in JSON.

In this part of your code:

<div class="form-group">
   @Html.Label("Projeto")
   <div>
      @Html.DropDownListFor(model => model.ProjetoId, new SelectList(ViewBag.ListaProjeto, "Value", "Text"), "Selecione", new { @class = "form-control" })
      @Html.ValidationMessageFor(m => m.ProjetoId, "", new { @class = "text-danger" })
   </div>
</div>
<div class="form-group">
   @Html.Label("Sub Projeto")
   <div>
      @Html.DropDownListFor(model => model.ProjetoId, new SelectList(ViewBag.ListaSubProjeto, "Value", "Text"), "Selecione", new { @class = "form-control" })
      @Html.ValidationMessageFor(m => m.ProjetoId, "", new { @class = "text-danger" })
   </div>
</div>

You are wanting to save activities (according to your @using (Html.BeginForm("CadastrarAtividades"...). You are with two DropDownList with the same id and name. If you need to save the two data on Database the ideal is that the fields are distinct.

  • It may sound like a stupid question, but you are passing the projectId with the parameter to the json, but I don’t understand where it is being used

  • @Fabiosouza Yes, he is not being used in the answer. But this is because the author of the question (AP) did not make clear how he wanted to use. That way, I didn’t change the code to not complicate.

Browser other questions tagged

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