Search database information by selecting a field

Asked

Viewed 1,920 times

0

How to select a field and pull the information related to it?

For example, I wanted to select a user and when I selected it appears in the fields type Name, Address, Cpf and etc all filled, searching for this information from the database.

I am using ASP . NET, C#, HTML, javascript.

If anyone can help out there, I’d appreciate it.

  • Face lack more clarity in the question. How do you want to select this field and where to answer? A select think solves the selection of the field, type: select campo1 from table. That (s) result(s) you take and put in a textbox, label and etc. Now, by the question I could not understand well.

  • Do you want to select this data from where exactly? Are you using any database? Which one? If it is a database, which tables do you want to search the data for? If it is not a database, what data structure is it using? Many questions need to be answered so that we can answer your...

  • Let me try to explain better, I am making a web system, has a field where I select the user, when selecting the user I wanted to bring all the information related to this user, as for example Name, Address, Cpf. I could tell?

  • I wanted to pull this information from the database. This user would have been previously registered.

  • I’m doing a dropdown that pulls all registered users, when selecting one, pull all this information from the database, filling these fields.

  • Right, get the information in the server-side database can you? You just want to know how to search and show?

  • Get the server side information I can, I want to play this information to the user side, to be displayed on the screen.

Show 2 more comments

3 answers

1

Use an ajax request to send the request with the selected user data:

// <select id="usuario">...</select>
// Instrução será chamada assim que o campo usuario for alterado
$(document).on('change', '#usuario', function(event){
    // Valor atual selecionado
    var user = $(this).val();
    $.ajax({
        url: 'endereco/da/pagina.aspx',
        type: 'GET',
        dataType: 'json',
        // No servidor com C# vai receber como Request.QueryString["usuario"]
        data: {usuario: user}, 
        success: function(json){
            // "nome" deve ser o id do campo input ex:
            // <input type="text" name="nome-do-usuario" id="nome">
            // Segue mesma regra para demais campos
            $('#nome').val(json.nome);
            $('#cpf').val(json.cpf);
            $('#endereco').val(json.endereco);
        },
        error: function (e){
            alert("Deu algo errado, examine o console para mais detalhes");
            console.log(e);
        }
    });
});

Using jQuery you get a great result with few lines. However you can get the same result with pure Javascript, just plaster a little on AJAX. And to enter the values in the fields you can use an instruction similar to:

var json = JSON.parse(xmlhttp.responseText);
document.getElementById("nome").value = json.nome;

I don’t program in ASP.NET, so I won’t be posting server code, but to learn more about how to encode a json see the documentation for MSDN.

0

Dude, it’s hard to answer your question because you have very little information about how you’re doing your application and how you’re accessing the data, but I think what you want is something like the following link example.

http://www.w3schools.com/asp/asp_ajax_database.asp

  • That’s about it, only I’ll select a user and pull the database information and fill in the <input type:text fields>

0


For this, you can make a method that returns all users in Json in his controller, would look like this:

Fetch method in controller:

    public JsonResult ObterPorId(int id)
        {  
 //ViewBag para listar todos os usuários
 ViewBag.Usuarios = Context.Usuarios.ToList()
                .Select(e => new SelectListItem
                {
                    Value = e.UsuarioId.ToString(),
                    Text = e.Nome,                    
                });
            var usuarios= context.usuarios.where(u => u.id == id).FirstOrDefault();

            return Json(usuarios, JsonRequestBehavior.AllowGet);
        }

And in his View, you can use the query Ajax, as @Kaduamaral suggested, so:

View:

<div class="col-md-2">
    Usuarios:
    @Html.DropDownList("ddlUsuarios", new SelectList(ViewBag.Usuarios, "value", "text"), new { @class = "form-control" })
</div>


id: <input id="id" name="id" /><br/>
Nome: <input id="nome" name="nome" /><br />
Cpf: <input id="cpf" name="cpf" />

@section Scripts {
    <script type="text/javascript">
        $('#ddlUsuarios').change(function () {
           // Valor atual selecionado
           var user = $(this).val();
           $.ajax({
               url: @Url.Content("~/") +'Usuarios/ObterPorId',
               type: 'GET',
               dataType: 'json',
               // No servidor com C# vai receber como Request.QueryString["usuario"]
               data: { id: user },
               success: function (json) {
                   // "nome" deve ser o id do campo input ex:
                   // <input type="text" name="nome-do-usuario" id="nome">
                   // Segue mesma regra para demais campos
                   //Lembrando que aqui e sensitive case, ou seja, diferenciando letras maiúsculas de minúsculas. 
                   $('#id').val(json.id);
                   $('#nome').val(json.nome);
                   $('#cpf').val(json.cpf);

               },
               error: function (e) {
                   alert("Deu algo errado, examine o console para mais detalhes");
                   console.log(e);
               }
           });
       });

    </script>
}
  • Actually I wanted to do on the same screen, on the screen would have the dropdown field to select the user, only on the same screen would have other fields like Name, Address and Cpf, but empty. When selecting the user in the dropdown these fields would be filled, with the information brought from the database referring to this user, previously registered.

  • It would be. But from what I’m seeing you need to look for a DropDownList? So change only once.

  • Actually I wanted to do on the same screen, on the screen would have the dropdown field to select the user, only on the same screen would have other fields like Name, Address and Cpf, but empty. When selecting the user in the dropdown these fields would be filled, with the information brought from the database referring to this user, previously registered.

  • I edited the answer based on the @Kaduamaral response. Test now and see if this is what you need.

  • In what you did when selecting the user, the id, name and Cpf fields are filled automatically?

  • Exactly @Italo.

  • I just don’t understand where you pull the dice from.

  • I am using the Obtenporid method to search for the selected user on DropDownList. And I’m filling in the DropDownList for ViewBag.Usuarios.

  • If I were to take this data from the database as it would look?

  • The way I put it, it’s searching in the database, in the users table.

Show 5 more comments

Browser other questions tagged

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