How to take an object property in a Session?

Asked

Viewed 483 times

0

In my Controller, 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");
        }
    }

Along those lines: Session["usuario"] = oUsuario; i inform that in my session I have stored an object of type Usuario.

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

Compiler Error Message: CS1061: 'Object' does not contain a Definition for 'usuario1' and no Extension method 'usuario1' Accepting a first argument of type 'Object' could be found (are you Missing a using Directive or an Assembly Reference?)

2 answers

4


Using objects in Session requires using a Cast.

Follow one of the forms in the example below:

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

Follow the code working on . NET Fiddle. https://dotnetfiddle.net/f2YfSQ

2

You will have to do the casting of Session:

@{
     var usuario = (Usuario)Session["usuario"];
}    

Browser other questions tagged

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