Slow problems with AJAX in ASP . NET MVC C#

Asked

Viewed 209 times

2

I have a problem of slowness in my AJAX response. I use the following code to search and return a list of results:

Javascript

function enviaBusca(url) {
    var resultado = $('#resultados'),
        mensagem = $('#mensagem'),
        palavras = $('input[type=hidden][name=palavrasTemp]').val(),
        palavraChave = $('#txt_palavra_chave').val(),
        valorMinimo = $('input[type=number][name=valor_minimo]').val(),
        valorMaximo = $('input[type=number][name=valor_maximo]').val(),
        buscaPublicado = $('')
    param = { 'buscaTermo': encodeURIComponent(palavraChave), 'palavrasBuscadas': palavras, 'buscaTipoImovel': get_lista_tipos_marcados(), 'buscaEstado': get_lista_estados_marcados(), 'buscaCidade': get_lista_cidades_marcadas(), 'buscaBairro': get_lista_bairros_marcados(), 'buscaCaptador': get_lista_captadores_marcados(), 'buscaPretensao': get_lista_pretensoes_marcadas(), 'buscaFinalidade': get_lista_finalidades_marcadas(), 'buscaSituacao': get_lista_situacoes_marcadas(), 'buscaValorMinimo': valorMinimo, 'buscaValorMaximo': valorMaximo, 'buscaPublicado': get_lista_publicados_marcadas() };

    $('#loading').removeClass('invisivel');
    resultado.empty();
    mensagem.addClass('invisivel');

    $.post(url, add_anti_forgery_token(param), function (response) {
        if (response) {
            if (response.length > 0) {
                resultado.removeClass('invisivel');
                for (var i = 0; i < response.length; i++) {
                    resultado.html(response);
                }
            }
        } else {
            resultado.addClass('invisivel');
            mensagem.html('Nenhum resultado foi encontrado com os filtros selecionados.').removeClass('invisivel');
        }
        $('#loading').addClass('invisivel');
    });
}

Controller

[AllowAnonymous]
        [HttpPost]
        public ActionResult Resultados(string buscaTermo, string palavrasBuscadas, List<int> buscaTipoImovel, List<int> buscaEstado, List<int> buscaCidade, List<int> buscaBairro, List<int> buscaCaptador, List<int> buscaPretensao, List<int> buscaFinalidade, List<int> buscaSituacao, int buscaValorMinimo, int buscaValorMaximo, List<int> buscaPublicado)
         {
            var palavrasTemp = palavrasBuscadas;
            if (palavrasTemp != "")
            {
                palavrasChave.Add(palavrasTemp);
            }
            palavrasChave.Add(buscaTermo);

            if (!Request.IsAuthenticated)
            {
                buscaSituacao.Clear();
                buscaSituacao.Add(1);
                buscaPublicado.Clear();
                buscaPublicado.Add(1);
            }

            var lista = ImoveisModel.RecuperarListaBusca(palavrasChave, buscaTipoImovel, buscaEstado, buscaCidade, buscaBairro, buscaCaptador, buscaPretensao, buscaFinalidade, buscaSituacao, buscaValorMinimo, buscaValorMaximo, buscaPublicado);
            ViewBag.TermoBuscado = palavrasChave;
            ViewBag.ListaImoveis = lista;
            ViewBag.QuantidadeRegistrosEncontrados = lista.Count();
            return PartialView(lista);
        }

JSON sent

param = { 'buscaTermo': encodeURIComponent(palavraChave), 'palavrasBuscadas': palavras, 'buscaTipoImovel': get_lista_tipos_marcados(), 'buscaEstado': get_lista_estados_marcados(), 'buscaCidade': get_lista_cidades_marcadas(), 'buscaBairro': get_lista_bairros_marcados(), 'buscaCaptador': get_lista_captadores_marcados(), 'buscaPretensao': get_lista_pretensoes_marcadas(), 'buscaFinalidade': get_lista_finalidades_marcadas(), 'buscaSituacao': get_lista_situacoes_marcadas(), 'buscaValorMinimo': valorMinimo, 'buscaValorMaximo': valorMaximo, 'buscaPublicado': get_lista_publicados_marcadas() }

The query runs until fast, the time varies from 20 to 600ms depending on the amount of results obtained but the problem is the return of AJAX, it takes a few minutes to assemble the screen and hide the loading div ... What could be wrong?

  • Welcome Cristiano. Have you checked if the problem is not in the Response loop? This loop doesn’t seem necessary, I don’t know what’s in Sponse, but regardless of the size it’s replacing the html N times but always the same value (Sponse).

  • So George, the loop is exactly to fill the list of results (in this case list of properties found with filters). With few results even returns fast but from 10 results it takes a lot of time to return, even freezes the screen preventing navigation or selection of other filters for the search.

  • It would be easier to get help if you post the controller code as well and give an example of how the return is. But assess if the answer below no longer meets your needs.

  • I added the Controller code, as I told the friend below my return is a List<Imoveismodel>.

2 answers

3

From what I see the query does not return only a JSON, but all the HTML already properly formatted. When you said the query was fast, this includes HTML formatting, or just the query in the database?

Formatting strings the wrong way can be very costly. Strings are generally immutable, meaning that when concatenating 2 strings, the compiler needs to relocate all of the variable’s memory.

In C#, the correct way to build long strings is with the Stringbuilder object.

If you are already doing this on your server, and the slowness is all Javascript, there is not much to do, recommend you replace the

for (var i = 0; i < response.length; i++) {
    resultado.html(response);
}

for

resultado.html(response.join(''));
  • Actually my return is a List<Imovel>, then in the results.cshtml I assemble html. When I referred to the loading time is just the model returned by JSON.

  • I’ve worked with tables that were too big to render at once. When you get to this point the best thing to do is to render 50-100 items at a time, and place an eventListener in the window scroll to render more items when the user scrolls the navigation bar to the end.

  • I understand, but in this case I do not believe to be a problem with the amount of records because even a query that returns 10 records takes about 5 minutes to complete, this when it does not give timeout. I have a list that brings all registered properties that does not use AJAX and loads quickly. In the search need AJAX so that the user applies filters to decrease the list without having to change pages all the time.

  • But then you are using AJAX only to filter the results of a list you already have on screen? It would not be better to use Javascript to filter these results?

  • Not really, I don’t think it helped my answer. What I said about having a list is in another session of the site, in the search I load the filters and from the moment I select the first filter I load the first list. From there to each user interaction with the filters (click on a checkbox) the AJAX query is made again applying the selected filter. I added in the reply the JSON that I send to the Model.

0


After breaking my head trying to find the problem in AJAX I stopped and thought about the obvious: what is the return? It is a list, being a list I do not need to go through the object "Answer" to build a list so I decided to remove the for and leave so:

Old code

$.post(url, add_anti_forgery_token(param), function (response) {
    if (response) {
        if (response.length > 0) {
            resultado.removeClass('invisivel');
            for (var i = 0; i < response.length; i++) {
                resultado.html(response);
            }
        }
    } else {
        resultado.addClass('invisivel');
        mensagem.html('Nenhum resultado foi encontrado com os filtros selecionados.').removeClass('invisivel');
    }
    $('#loading').addClass('invisivel');
});

New code

$.post(url, add_anti_forgery_token(param), function (response) {
    if (response.length > 0) {
        resultado.removeClass('invisivel');
        resultado.html(response);
    } else {
        resultado.addClass('invisivel');
        mensagem.html('Nenhum resultado foi encontrado com os filtros selecionados.').removeClass('invisivel');
    }
    $('#loading').addClass('invisivel');
});

Thank you all for the answers and I leave here the solution so that if someone else has similar problems can solve.

  • That’s exactly what I told you in your question. hehehe ! :)

Browser other questions tagged

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