ASP.NET MVC: Save an int variable from a select query on sql server

0

My problem is as follows. I have a code for a login, where I keep the username of the user who logged in Session["USERNAME"] . What I'm trying to do is put in my variable wea the ID of the user who just logged in using his username in a sql query. As it is logical I have not obtained any result and that is why I come here to see if someone can tell me what would be the right way to do what I want to do. Thanks for your answers.

 public ActionResult Login(EMPLEADOS empleado)
    {
            using (ConnectionContext db = new ConnectionContext())
            {
                var usr = db.EMPLEADOS.Where(u => u.USERNAME == empleado.USERNAME && u.PASSWORD == empleado.PASSWORD).FirstOrDefault();
                if (usr != null)
                {
                int wea = db.Database.ExecuteSqlCommand("SELECT ID FROM dbo.EMPLEADOS WHERE USERNAME = @empleado.USERNAME");
                    Session["ID"] = wea.ToString();
                    Session["USERNAME"] = empleado.USERNAME.ToString();
                    return RedirectToAction("Logeado");
                }
                else
                {
                    ModelState.AddModelError("", "Usuario o Contraseña invalido");
                }
            }
        return View();
    }
    
asked by Ezio Auditore 18.04.2018 в 04:18
source

1 answer

0

In the variable usr you already have the logged in user. If it is different from null, it is because it was found in the database.

I hope you serve

    public ActionResult Login(EMPLEADOS empleado)
    {
       using (ConnectionContext db = new ConnectionContext())
       {
          var usr = db.EMPLEADOS.Where(u => u.USERNAME == empleado.USERNAME && u.PASSWORD == empleado.PASSWORD).FirstOrDefault();
          if (usr != null)
          { 
             // Se encontró el usuario en base de datos
             int wea = usr.Id;
             Session["ID"] = usr.Id.ToString();
             Session["USERNAME"] = usr.USERNAME.ToString();
             return RedirectToAction("Logeado");
          }
          else
          {
              ModelState.AddModelError("", "Usuario o Contraseña invalido");
          }
       }
        return View();
    }
    
answered by 18.04.2018 в 06:13