how to access session in model asp.net mvc

kalu picture kalu · Jun 27, 2012 · Viewed 16.2k times · Source

How can I access to the session from the Model?

I try to use:

public IQueryable<EstudentsViewModel> GetEstudentsProjected(decimal? Code)
        {
           .
           .   
           .
           decimal id;
           id = (decimal)Session["Consul"];
           .
           .
           .
        }

Appear: The name 'Session' does not exist in the current context

Answer

Darin Dimitrov picture Darin Dimitrov · Jun 27, 2012

How can I access to the session from the Model?

You could always perform the following pornography:

HttpContext.Current.Session["Consul"]

But please, oh my holy Earth please, promise me to never perform such a crime.

A Model should never know what a Session is. A Session is a web term and the Model should be completely agnostic of it. You should pass the information that the Model requires from the Controller which has access to the Session.

So check this out:

public IQueryable<EstudentsViewModel> GetEstudentsProjected(decimal? Code, decimal id)
{
    ...
}

And when invoking this method from the controller you will simply pass the value from the Session because the Controller has access to it.