Two types of search in the same textbox

Asked

Viewed 403 times

1

I wonder if it is possible to search two types of variables (one at a time) in a single textbox. Example:

public ActionResult Index(string pesquisa)
{
    var usuario =  from u in db.usuario
                  select u;

    if (!String.IsNullOrEmpty(pesquisa))
    {
        usuario = usuario.Where(p => p.nomecompleto.Contains(pesquisa));
    }

    return View(usuario);
}

This my code above returns registered users of the site according to the name. I would like the site administrator to have the option to search users both by name and by CPF (which has been defined as int), simply typing the name or CPF.

Could someone explain if it is possible to do this? And if possible, I would like to take advantage of the code above.

1 answer

2


It is possible. Just make your search string also search by CPF.

I don’t know her user class, but I suppose she has a field CPF which is a String already formatted, and what comes from the screen is also a String CPF already formatted within the field pesquisa:

public ActionResult Index(string pesquisa)
{
    var usuario =  from u in db.usuario
                  select u;

    if (!String.IsNullOrEmpty(pesquisa))
    {
        usuario = usuario.FirstOrDefault(p => p.nomecompleto.Contains(pesquisa) || p.cpf.Contains(pesquisa));
    }

    return View(usuario);
}
  • There is Some difference between using Where or Firstordefault?

  • Yes, the FirstOrDefault already returns the first query element passed as a predicate, or null if there are no results. The Where returns an iterable element that needs other methods to become the desired result. For your case, FirstOrDefault is the most recommended.

Browser other questions tagged

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