andres descalzo
andres descalzo

Reputation: 14967

ASP.NET MVC 1 - Calling the Session object in ViewModel

How can I call the Session in ViewModel?, Reference to "Session [...]" or " HttpContext.Session [..]" not exist in this context

Upvotes: 3

Views: 3295

Answers (2)

Steven Pardo
Steven Pardo

Reputation: 440

try

HttpContext.Current.Session[..]

Upvotes: 6

John Gietzen
John Gietzen

Reputation: 49544

The general idea is that you "shouldn't."

Your controller should provide all of the information that the view needs.

However, it may be worthwhile to pass the session (or pieces of it) along with the ViewModel.

The way I handle this is, I have a base class for all of my view models that have access to the controller. They can then directly query the controller for specific objects from the session without ever exposing the session directly to the view.

BaseView.cs

public abstract class BaseView<TModel> : SparkView<TModel> where TModel : ControllerResponse
{
    // Stuff common to all views.
}

ControllerResponse.cs (base model for all views)

public class ControllerResponse
{
    private BaseController controller = null;

    private ControllerResponse() { }

    public ControllerResponse(BaseController controller)
    {
        this.controller = controller;
    }

    // Here, you would place all of the methods that the BaseView should have access to.
}

Upvotes: 5

Related Questions