Query using Linq to sql in Asp.net MVC

Asked

Viewed 481 times

1

I have a question about how to return the records according to the query. I don’t know what could be wrong, but the query is not returning according to what was past.

I have my controller:

public ActionResult Index()
{
    //retornar todos os registros  
    sistema_mobileEntities dao = new sistema_mobileEntities();
    TempData["titulo1"] = "Consulta Registro";
    return View(dao.cliente.ToList());

}

[HttpPost]
public ActionResult Index(string recebeNome, int recebeOpcao)
{

    try
    {
        sistema_mobileEntities dao = new sistema_mobileEntities();

        if (recebeOpcao == 1)
        {
            var sql = from c in dao.cliente
                    where SqlMethods.Like(c.nome, recebeNome.Trim() + "%")
                    select c;

            TempData["opcao1"] = "nome";
        }

        if (recebeOpcao == 2)
        {
            var sql = from c in dao.cliente
                      where SqlMethods.Like(c.pai, recebeNome.Trim() + "%")
                      select c;

            TempData["opcao2"] = "pai";
        }

        if (recebeOpcao == 3)
        {
            var sql = from c in dao.cliente
                      where SqlMethods.Like(c.mae, recebeNome.Trim() + "%")
                      select c;

            TempData["opcao3"] = "mae";
        }

        return View(dao.cliente.ToList());
    }
    catch (Exception ex)
    {
        return Json("Erro ao consultar usuario" + ex.Message);
    }


}

1 answer

3


You are not returning the variable that was used in the search.

The line:

return View(dao.cliente.ToList());

Should be:

return View(sql.ToList());
  • //generates an error Error The name 'sql' does not exist in the Current context Return View(sql.Tolist());

  • @itasouza you have to create the sql outside the if. IQueryable<Cliente> sql;

  • I added this, without sql = null generates another error Iqueryable<client> sql; sql = null; worked, thanks!

Browser other questions tagged

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