How do I get a property of an object in a Session?

0

In my Controller , I have a ActionResult responsible for logging in the user:

[HttpPost]
public ActionResult Valida(string pUsuario, string pSenha)
{
    oUsuario = modelOff.usuarios.SingleOrDefault(p => p.usuario1 == pUsuario && p.senha == pSenha);

    if (oUsuario == null)
        {
            Session["usuario"] = "Senha ou usuário incorretos";
            return RedirectToAction("Index");
        }
        else
        {
            Session["usuario"] = oUsuario;
            return RedirectToAction("BPAC");
        }
    }

In this line: Session["usuario"] = oUsuario; I inform that in my session I have stored an object of type Usuario .

How do I show some property of it in View ? I tried like this: @Session["usuario"].usuario1 but it was not. I received the error below:

  

Compiler Error Message: CS1061: 'object' does not contain a definition for 'user1' and no extension method 'user1' accepting a first argument of type 'object' could be found an assembly reference?)

    
asked by anonymous 30.08.2017 / 03:36

2 answers

4

Using objects in Session requires using Cast.

Here's one of the ways in the example below:

@{var user = Session["Usuario"] as Usuario;}            
<h1>@user.Email</h1>

Follow the code working in .NET Fiddle. link

    
30.08.2017 / 04:04
2

You will have to cast the session:

@{
     var usuario = (Usuario)Session["usuario"];
}    
    
30.08.2017 / 03:56