Error filling cascading combobox: Failed to load Resource: net::ERR_CONNECTION_RESET

Asked

Viewed 57 times

0

I am trying to create a method to register a coefficient, this coefficient is linked to a table, which in turn belongs to a Concourse, the idea is to select the Concourse in the first combobox and be filled automatically the tables in the second, to select the table that has the coefficients... however returns me an error from: Failed to load Resource: net:ERR_CONECTION_RESET.

Code of the Controller:

//para json
    [HttpGet]
    [EnableCors("MinhaPolitica")] // AQUI!!!
    public JsonResult FiltraConvenios(int id)
    {
        ViewData["ConvenioId"] = new SelectList(_context.Set<Convenio>(), "Id", "Nome");
        ViewBag.Convenios = _context.Convenio.ToList();
        List<SelectListItem> Lista = new List<SelectListItem>();
        var Dados = _context.Tabela
                .Where(c => c.ConvenioID == id)
                .OrderBy(c => c.Convenio)
                .Select(t => new
                { t.Id, t.Nome });
        foreach (var Linha in Dados)
        {
            Lista.Add(new SelectListItem()
            {
                Value = Linha.Id.ToString(),
                Text = Linha.Nome,
                Selected = false
            });
        }
        return Json(Lista);
    }

View code:

                <div class="ibox-content">
                <div class="col-md-12">
                    <form asp-action="Create">
                        <div class="row">
                            <div class="col-md-2">
                                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                                <div class="form-group">
                                    <label asp-for="Valor" class="control-label"></label>
                                    <input asp-for="Valor" class="form-control" />
                                    <span asp-validation-for="Valor" class="text-danger"></span>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label asp-for="DataAtivo" class="control-label"></label>
                                    <input asp-for="DataAtivo" class="form-control" />
                                    <span asp-validation-for="DataAtivo" class="text-danger"></span>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label asp-for="ConvenioID" class="control-label"></label>
                                    <select id="SelectConvenio" asp-for="ConvenioID" class="form-control" asp-items="ViewBag.ConvenioID"></select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label asp-for="TabelaID" class="control-label"></label>
                                    <select id="SelectTabela" asp-for="TabelaID" class="form-control"></select>
                                </div>
                            </div>
                            <div class="col-md-1" style="margin-top:26px">
                                <div class="form-group">
                                    <input type="submit" value="Salva" class="btn btn-primary" />
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

Jquery code:

 <script>


$(document).ready(function () {
    $('#SelectConvenio').change(function() {
        console.log('@Context.Request.Host');
        console.log("clicou select convenio e mudou");
        //limpa seletc ESCRAVO
        $('#SelectTabela').empty();
        console.log("passou por remoção da lista");

        //Guarda opção que foi selecionada no Select MESTRE
        var OpcaoAtual = $(this).val();
        $('#SelectTabela').append($('<option></option>').val("0").html('Selecione uma Tabela'));
        var x = document.getElementById("SelectTabela");
        var option = document.createElement("option");

        //Adiciona uma opção tipo Slecione um Valor
        //option.value = "0"
        x.add(option);

        //Mancada para forçar redraw - pode não ser necessário
        var element = document.getElementById('SelectTabela');
        var n = document.createTextNode(' ');
        var disp = element.style.display; // don't worry about previous display style
        element.appendChild(n);
        element.style.display = 'none';
        setTimeout(function() {
            element.style.display = disp;
            n.parentNode.removeChild(n);
        }, 20);
        //fim do redraw - este bloco pode ser retirado

        //para conferir a opção select MESTRE selecionada
        console.log("Opcao Atual" + OpcaoAtual);

        //monta URL completa, com parâmetro
        var url = 'http://' + '@Context.Request.Host/Coeficientes/FiltraConvenios' + OpcaoAtual;
        //verifica url montada
        console.log(url);
        console.log('idConvenio = ' + $('#SelectConvenio').val());

        //chama AJAX
        $.ajax({
            type: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'text/plain'
            },
            dataType: 'json',
            url: url,
            success: function(data) {
                console.log(data);
                callbackFunction(data); //IMPORTANTE
            }
        });

        //Carrega o select ESCRAVO
        function callbackFunction(resultData) {
            // alert("entrei");
            var items = '<option value="0"><<Selecione uma Tabela>></option>';
            //console.log(resultData);
            $.each(resultData, function(i, tabela) {

                items += "<option value='" + tabela.value + "'>" + tabela.text + "</option>";
                $("#SelectTabela").append("<option value='" + tabela.value + "'>" + tabela.text + "</option>");
                //confere no console
                console.log("<option value='" + tabela.value + "'>" + tabela.text + "</option>");

            });
            //confere no console
            console.log(items);
            //truque para tirar linha em branco
            $('#SelectTabela option:eq(' + 1 + ')').remove(); //retira branco

        }
    })

    //função auxiliar REDRAW
    //https://gist.github.com/mgHenry/6154611
    jQuery.fn.redraw = function() {
        jQuery(this).each(function() {
            this.style.display = 'none';
            this.offsetHeight; // no need to store this anywhere, the reference is enough
            this.style.display = 'block';
        })
    };
});

</script>

Error: inserir a descrição da imagem aqui

  • What is the name of the json file?

  • I do not create a json file, I just pass the "List" variable in the json (List)

  • Verifque se var url = 'http://' + '@Context.Request.Host/Coeficientes/FiltraConvenios' is mounting the url correctly and add a / if you already have the route to the {id} or pass the querystring '/?id='+OpcaoAtual

  • And why the question of CORS with @Context.Request.Host, if the request is on the same host, just make the request from the root... '/Coeficientes/FiltraConvenios/'

1 answer

0

Refactoring the code, I passed: var url = 'http://' + '@Context.Request.Host/Coefficients/Filtraconvenios' with https and started returning the data.

Browser other questions tagged

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