1

I'm trying to create a strongly-typed session object. Let's assume I want to store the user's name and email in the session. My base controller would take care of that, so I can always assume that the values are present in the session.

Currently, I can refer to them in my Razor view like this:

Email: @Session["Email"]<br/>
Name: @Session["Name"]<br/>

What I would like is to do something like this:

Email: @Session.Email<br/>
Name: @Session.Name<br/>

I think that the way to do this would be to extend the HttpContext.Session object. Something similar to:

class MySession : HttpSessionState {

    public string Email { get; set; }
    public string Name { get; set; }

}

I tried creating my own session provider, as described here, but this does not get exposed in the HttpContext, Controller or View.

There is a good workaround using extension methods as described here. This results in a slightly different syntax and it's not exactly what I wanted:

Email: @Session.Email()<br/>
Name: @Session.Name()<br/>

Is there a better way of doing this?

Thanks!

mkorman
  • 948
  • 2
  • 10
  • 27

1 Answers1

0

You can use TempData. I advice for you look at this,this or this

Community
  • 1
  • 1
Elvin Mammadov
  • 25,329
  • 11
  • 40
  • 82
  • Thanks for the suggestion. I'm not sure it's what I want. I wanted to persist something in the session so that it's accessible from anywhere in the application and lasts throughout the whole session lifecycle. TempData does not seem to do this. – mkorman Aug 01 '13 at 15:00