Viacep does not fill in user address data (Website on the .NET platform)

Asked

Viewed 1,392 times

3

I’m developing a web application on the platform. NET and I thought of making the user type the zip code of his address and automatically he would fill the text boxes with data of street, neighborhood, city and state. But in my code it doesn’t work, I don’t know why.

Here is my code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Novo Registro</title>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>
    <script src="https://fiddle.jshell.net/js/lib/dummy.js"></script>


    <script type='text/javascript'>//<![CDATA[
        window.onload=function(){
            $("#txtCPF").keydown(function(){
                try {
                    $("#txtCPF").unmask();
                } catch (e) {}

                var tamanho = $("#txtCPF").val().length;

                if(tamanho < 11){
                    $("#txtCPF").mask("999.999.999-99");
                } else if(tamanho >= 11){
                    $("#txtCPF").mask("99.999.999/9999-99");
                }                   
            });
        }//]]> 
</script>
    <!-- Adicionando Javascript -->
    <script type="text/javascript">

    function limpa_formulario_cep() {
            //Limpa valores do formulário de cep.
            document.getElementById("#txtRua").value=("");
            document.getElementById('#txtBairro').value=("");
            document.getElementById('#txtCidade').value=("");
            document.getElementById('#txtEstado').value=("");
    }

    function meu_callback(conteudo) {
        if (!("erro" in conteudo)) {
            //Atualiza os campos com os valores.
            document.getElementById('#txtRua').value=(conteudo.logradouro);
            document.getElementById('#txtBairro').value = (conteudo.bairro);
            document.getElementById('#txtCidade').value = (conteudo.localidade);
            document.getElementById('#txtEstado').value = (conteudo.uf);
        } //end if.
        else {
            //CEP não Encontrado.
            limpa_formulario_cep();
            alert("CEP não encontrado.");
        }
    }

    function pesquisacep(valor) {
        //Nova variável "cep" somente com dígitos.
        var cep = valor.replace(/\D/g, '');

        //Verifica se campo cep possui valor informado.
        if (cep != "") {

            //Expressão regular para validar o CEP.
            var validacep = /^[0-9]{8}$/;

            //Valida o formato do CEP.
            if(validacep.test(cep)) {

                //Preenche os campos com "..." enquanto consulta webservice.
                document.getElementById('#txtRua').value = "...";
                document.getElementById('#txtBairro').value = "...";
                document.getElementById('#txtCidade').value = "...";
                document.getElementById('#txtEstado').value = "...";

                //Cria um elemento javascript.
                var script = document.createElement('script');

                //Sincroniza com o callback.
                script.src = '//viacep.com.br/ws/'+ cep + '/json/?callback=meu_callback';

                //Insere script no documento e carrega o conteúdo.
                document.body.appendChild(script);

            } //end if.
            else {
                //cep é inválido.
                limpa_formulario_cep();
                alert("Formato de CEP inválido.");
            }
        } //end if.
        else {
            //cep sem valor, limpa formulário.
            limpa_formulario_cep();
        }
    };

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h3>Cadastro de Clientes - Novo Registro</h3>
        <h5>Obs.: Campos sinalizados com *(asterisco) são de preenchimento obrigatório!</h5>

        <asp:TextBox ID="txtNome" runat="server" Width="384px" placeholder="Nome*"></asp:TextBox>
        <asp:RequiredFieldValidator ID="txtNomeValidator" runat="server" ControlToValidate="txtNome" Display="Dynamic" ForeColor="Red" ErrorMessage="*"></asp:RequiredFieldValidator>

        <asp:TextBox ID="txtFantasia" runat="server" Width="384px" placeholder="Fantasia"></asp:TextBox><br /> 

        <asp:TextBox ID="txtCPF" runat="server" Width="384px" placeholder="CPF ou CNPJ"></asp:TextBox><br /> 
        <asp:TextBox ID="txtCEP" runat="server" Width="70px" placeholder="CEP*" AutopostBack="true"></asp:TextBox><br />
        <asp:TextBox ID="txtLogradouro" runat="server" Width="305px" placeholder="Logradouro"></asp:TextBox><br />
        <asp:TextBox ID="txtNumero" runat="server" Width="80px" placeholder="Número"></asp:TextBox><br />
        <asp:TextBox ID="txtComplemento" runat="server" Width="100px" placeholder="Complemento"></asp:TextBox><br />
        <asp:TextBox ID="txtBairro" runat="server" Width="200px" placeholder="Bairro"></asp:TextBox><br />
        <asp:TextBox ID="txtCidade" runat="server" Width="200px" placeholder="Cidade"></asp:TextBox><br />
        <asp:TextBox ID="txtEstado" runat="server" Width="50px" placeholder="Estado"></asp:TextBox><br />

        <asp:Button ID="btnSalvar" runat="server" Text="Salvar"/>

       </div>
    </form>
</body>
</html>

my code-Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class insert : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        txtCEP.Attributes.Add("onblur", "pesquisacep(this.value);");
    }

}

It works on JSBIN: http://output.jsbin.com/baxuyumace

Could someone help me with this, please?

  • Hello Cassia, welcome to Stackoverflow in English. Could you be more specific, because it doesn’t work? Is there an error message? Try to isolate the problem further.

  • Thank you, drmcarvalho :). So, I go to type the zip code and the screen updates, but the fields are not filled :(

2 answers

3


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Novo Registro</title>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>
    <script src="https://fiddle.jshell.net/js/lib/dummy.js"></script>

    <script type='text/javascript'>//<![CDATA[
        window.onload=function(){
            $("#txtCPF").keydown(function(){
                try {
                    $("#txtCPF").unmask();
                } catch (e) {}

                var tamanho = $("#txtCPF").val().length;

                if(tamanho < 11){
                    $("#txtCPF").mask("999.999.999-99");
                } else if(tamanho >= 11){
                    $("#txtCPF").mask("99.999.999/9999-99");
                }                   
            });
        }//]]> 
    </script>
    <!-- Adicionando Javascript -->
    <script type="text/javascript" >

        $(document).ready(function() {

            function limpa_formulario_cep() {
                // Limpa valores do formulário de cep.
                $("#txtLogradouro").val("");
                $("#txtBairro").val("");
                $("#txtCidade").val("");
                $("#txtEstado").val("");
            }

            //Quando o campo cep perde o foco.
            $("#txtCEP").blur(function() {

                //Nova variável "cep" somente com dígitos.
                var cep = $(this).val().replace(/\D/g, '');

                //Verifica se campo cep possui valor informado.
                if (cep != "") {

                    //Expressão regular para validar o CEP.
                    var validacep = /^[0-9]{8}$/;

                    //Valida o formato do CEP.
                    if(validacep.test(cep)) {

                        //Preenche os campos com "..." enquanto consulta webservice.
                        $("#txtLogradouro").val("...")
                        $("#txtBairro").val("...")
                        $("#txtCidade").val("...")
                        $("#txtEstado").val("...")

                        //Consulta o webservice viacep.com.br/
                        $.getJSON("//viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {

                            if (!("erro" in dados)) {
                                //Atualiza os campos com os valores da consulta.
                                $("#txtLogradouro").val(dados.logradouro);
                                $("#txtBairro").val(dados.bairro);
                                $("#txtCidade").val(dados.localidade);
                                $("#txtEstado").val(dados.uf);
                            } //end if.
                            else {
                                //CEP pesquisado não foi encontrado.
                                limpa_formulario_cep();
                                alert("CEP não encontrado.");
                            }
                        });
                    } //end if.
                    else {
                        //cep é inválido.
                        limpa_formulario_cep();
                        alert("Formato de CEP inválido.");
                    }
                } //end if.
                else {
                    //cep sem valor, limpa formulário.
                    limpa_formulario_cep();
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h3>Cadastro de Clientes - Novo Registro</h3>
        <h5>Obs.: Campos sinalizados com *(asterisco) são de preenchimento obrigatório!</h5>

        <asp:TextBox ID="txtNome" runat="server" Width="384px" placeholder="Nome*"></asp:TextBox>
        <asp:RequiredFieldValidator ID="txtNomeValidator" runat="server" ControlToValidate="txtNome" Display="Dynamic" ForeColor="Red" ErrorMessage="*"></asp:RequiredFieldValidator>

        <asp:TextBox ID="txtFantasia" runat="server" Width="384px" placeholder="Fantasia"></asp:TextBox><br /> 

        <asp:TextBox ID="txtCPF" runat="server" Width="384px" placeholder="CPF ou CNPJ"></asp:TextBox><br /> 
        <asp:TextBox ID="txtCEP" runat="server" Width="70px" placeholder="CEP*" AutopostBack="true" AcceptsTab="True"></asp:TextBox><br />
        <asp:TextBox ID="txtLogradouro" runat="server" Width="305px" placeholder="Logradouro"></asp:TextBox><br />
        <asp:TextBox ID="txtNumero" runat="server" Width="80px" placeholder="Número"></asp:TextBox><br />
        <asp:TextBox ID="txtComplemento" runat="server" Width="100px" placeholder="Complemento"  AutopostBack="true"></asp:TextBox><br />
        <asp:TextBox ID="txtBairro" runat="server" Width="200px" placeholder="Bairro"></asp:TextBox><br />
        <asp:TextBox ID="txtCidade" runat="server" Width="200px" placeholder="Cidade"></asp:TextBox><br />
        <asp:TextBox ID="txtEstado" runat="server" Width="50px" placeholder="Estado"></asp:TextBox><br />

        <asp:Button ID="btnSalvar" runat="server" Text="Salvar"/>

       </div>
    </form>
</body>
</html>

I managed to solve it. For those who are interested, the code is there.

  • marks as resolved his own response :)

  • @Cassia, if you have solved it yourself, you can mark your own response as resolved so that others can take advantage of the solution ;)

  • Thank you, friends. I have already marked my answer. I hope to continue to contribute to the community. bjs

  • @Cassia liked the code, thanks for sharing!

2

I use the Post Office itself.

Example of Consumption:

            using (var ws = new AtendeClienteClient())
        {
            var resposta = ws.consultaCEP(cep);

            Console.Clear();
            Console.WriteLine(String.Format("Endereço : {0}", resposta.end));
            Console.WriteLine(String.Format("Bairro : {0}", resposta.bairro));
            Console.WriteLine(String.Format("Cidade : {0}", resposta.cidade));
            Console.WriteLine(String.Format("UF : {0}", resposta.uf));
            Console.WriteLine(String.Format("CEP : {0}", resposta.cep));
            Console.WriteLine("");
            Console.WriteLine("PRESSIONE QUALQUER TECLA PARA CONTINUAR...");

            Console.ReadKey();
        }

The WSDL can be found at: WSDL Correios

Example of import and implementation in C#: Example in C#

Video Explanatory:

Example on Youtube

  • Roger, your answer is great, but the content is not in Stackoverflow, you would be able to edit and add the code, and then mention the tutorial Consuming Webservice of the Post Office - ZIP, and your Git repository, etc.

  • 1

    David the code is the simple consumption of WS. I believe the interesting is the mail WSDL that is not known to all.

Browser other questions tagged

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