Problems loading cascaded dropdownlist whose field is created dynamically - Asp.net MVC

Asked

Viewed 130 times

1

I’m having trouble loading a DROPDOWNLIST that is dynamically created. When selecting a CONTACT FORM, I need the dropdownlist CONTACT TYPE to be loaded with the related options. The problem is that I am creating the fields dynamically and when I need to call them, I use the id attribute of both... In the dropdownlist CONTACT FORM, I created a change event that takes the value of the field and makes a query in the database to load the second dropdownlist CONTACT FORM. The problem is that the dropdownlist field CONTACT FORM will be repeated several times and the id index will be incremented... I needed, in the change event, to save the dropdownlist id CONTACT FORM to load correctly when necessary... Or make another mareira (I accept suggestions). Someone knows how to help me?

Big hug to all!

inserir a descrição da imagem aqui

HTML:

<div class="col-md-3">
    <label asp-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" class="control-label lb-pf-forma-contato">Forma de Contato</label>
    <select asp-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" asp-items="@Model.PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.FormasContatos" data-id="@Model.PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" title="Selecione uma opção" class="form-control show-tick show-menu-arrow sel-pf-forma-contato"><option value=""></option></select>
    <span asp-validation-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" class="text-danger val-pf-forma-contato"></span>
</div>
<div class="col-md-3">
    <label asp-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.ContatoTipo" class="control-label lb-contato-tipo">Tipo de Contato</label>
    <select asp-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.ContatoTipo" asp-items="@Model.PessoaFisicaViewModel.PessoasFisicasContatosTipos" title="Selecione uma opção" class="form-control show-tick show-menu-arrow sel-contato-tipo"></select>
    <span asp-validation-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel[i].PessoaFisicaFormaContatoTipoViewModel.ContatoTipo" class="text-danger val-contato-tipo"></span>
</div>

IDS generated:

  • CONTACT FORM - id="Personal Physiphysicsmodel_personal Physicscontact Uscontact Usviewmodel_0__personal Physicscontact Uspoviewmodel_personal Physicscontact Us"

  • TYPE OF CONTACT id="Personal Physicscaviewmodel_person"

JAVASCRIPT:

$(document).ready(function () {
        $('#div-contatos').on("change", ".sel-pf-forma-contato", function (e) {
            //var teste = $(this).attr("data-id");
            //alert(teste);
            $.ajax({
                url: "/pessoa-fisica-gerenciar/getContatoTipo",
                type: "POST",
                data: { pessoaFisicaFormaContato: $(this).val() },
                traditional: true,
                success: function (result) {
                    var select = $("#contato-tipo-select");// Aqui carrega o dropdownlist TIPO DE CONTATO
                    alert(select);
                    select.empty();
                    select.append($('<option/>', {
                        value: "",
                        text: ""
                    }));
                    $.each(result, function () {
                        $.each(this, function (i, item) {
                            select.append($('<option/>', {
                                value: item.value,
                                text: item.text.toUpperCase()
                            }));
                        });
                        //select.append($('<option/>', {
                        //    value: itemData.Value,
                        //    text:  itemData.Text
                        //}));
                    });
                },
                error: function () {
                    alert("Something went wrong call the police");
                }
            });
        });

    });
  • You’d get the id with $(this).attr("id") (jQuery) or this.id (JS pure).

  • That’s the problem @Sam!!! If I have two or more dropdownlists, the ids will have index ([0], [1], [2]...)

  • Ex: id="Personfisicaviewmodel_person"

  • You wanted to get the id without the numbers?

  • Take a look at the print where I marked with red arrows... When selecting an option in the contact form dropdown, I have to record somehow the id of the dropdown "contact type" that is in the same Row... If I have more than one Row there is no way to load the records into the dropdown...

  • The problem is that as I create a new Row, the id will change and being generated an index for each field... Look at the name of the ids in print..

  • From what I understood then is that you do not know which dropdown to fill when changing the "contact form" because the id of the "contact type" changes with each line? Each pair of dropdown is in one .row?

  • That’s right!!! I thought about saving the id of the second combobox in the change event of the first combo.... and then using it.. but I don’t know how to do that...

Show 4 more comments

2 answers

1


Don’t worry about taking the element by the id, which may even be expendable. You can catch by the class inside the same Row of the dropdown that triggered the event:

var select = $('#div-contatos')
             .closest(".row")
             .find(".sel-contato-tipo");

1

friend I don’t know if I got it right but come on.

in the action of this controller:

public IActionResult NOMEDAVIEW()
{
    ViewBag.FormaContatos = new SelectList(_db.FORMACONTATODB.ToList(), "ID", "NOME");
    return View();

}

Na View

@model IEnumerable<model que voce estava usando>
<div class="col-md-3">
<label asp-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel.PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" class="control-label lb-pf-forma-contato">Forma de Contato</label>
<select asp-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel.PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" onchange="ChamarFunction(this.id)" asp-items="@ViewBag.FormaContatos" id="@Model.PessoaFisicaViewModel.PessoasFisicasContatosViewModel.PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" title="Selecione uma opção" class="form-control show-tick show-menu-arrow sel-pf-forma-contato"><option value=""></option></select>
<span asp-validation-for="PessoaFisicaViewModel.PessoasFisicasContatosViewModel.PessoaFisicaFormaContatoTipoViewModel.PessoaFisicaFormaContato" class="text-danger val-pf-forma-contato"></span></div>

<div class="col-md-3" id="out"></div>

In javascript

function ChamarFunction(id) {
$.ajax({
    dataType: "json",
    type: "POST",
    url: '/Controller/TipoContato',
    data: {
        'ID': id
    },
    success: function (data) {
        if (data != null) {
            var opts = "";
            opts += '<select id="idFormaContato" class="form-control">'
            opts += '<option value="" selected disabled hidden>Selecione</option>'
            $(data).each(function (i) {
                opts += '<option value="' + data[i].id + '">' + data[i].nome + ' </option>'
                //data[i].atributo da sua classe , qualquer coisa coisa coloque um ponto de parada no navegador e veja o objeto q está recebendo no data
            });
            opts += '</select>'
            $("#out").html(opts);
        }else{
            $("#out").html("Sem tipo de contato");   
        }

    },
    error: function (error) {
        alert('Erro')
    }
});

};

Again in the controller

public IActionResult TipoContato(int ID)// mesmo nome no método do ajax (TipoContato)
{
   var lista = _db.TipoContatoDB.Where(c => c.TipoContatoID == id).ToList();
   if(lista != null) 
   {
      return Json(lista);
   }       
   return Json(null);
}

anything comments there if error

Browser other questions tagged

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