How can I call the Session in ViewModel?, Reference to "Session [...]" or " HttpContext.Session [..]" not exist in this context
+2
A:
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.
}
John Gietzen
2010-02-08 16:36:56
+1 for "The general idea is that you shouldn't."
mxmissile
2010-02-08 16:58:01
+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.
andres descalzo
2010-02-08 17:35:32
Sorry, calling for "System.Web" / "using System.Web;" I can get a Session
andres descalzo
2010-02-08 17:30:20
sorry forgot to add the fully qualified name. great to hear that you got it working.
Steven Pardo
2010-02-08 17:41:03