3

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

2 Answers 2

6

try

HttpContext.Current.Session[..]
Sign up to request clarification or add additional context in comments.

3 Comments

Reference to "HttpContext..." not exist in this context
Sorry, calling for "System.Web" / "using System.Web;" I can get a Session
sorry forgot to add the fully qualified name. great to hear that you got it working.
5

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.
}

1 Comment

+1 For an answer, in my case because this is a ViewModel which corresponds to a "ascx", is simpler (not to correct), calling for System.Web.HttpContext.Current.Session. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.