Is there any way to access session on view page by creating common method in controller also want to access session in controller by common method in ASP.Net MVC.
问题:
回答1:
are you using razor view engine?
View:
@{ var sessionVar = Session["key"]; //it's object }
Controller:
public ActionResult Method() {
var sessionVar = this.Session["..."]; //
}
the common way to call this object is: HttpContext.Current.Session
I don't know what you meant by 'common'. the provided session object is common for user session no matter where you will call for it.
But in fact you shouldn't try to use session it's ugly - try to do some search about ViewBag / ViewData and then try to search why you shouldn't use them as well. :)
回答2:
Am new to MVC but I think I know what you're trying to do. You don't need to create a 'common' method to achieve that. @trn Solution should work but it might throw Null reference exceptions if accessed in "View" without using "HttpContext.Current.Session" object for two possible reasons:
- Session["key"] is null.
- incorrect reference to Session["key"] in View and/or Controller.
Using "HttpContext.Current.Session" object is great way to achieve what you're looking for and make sure the Session["key"] is not null. For example:
View:
@{
var sessionVar = Session["key"]; // might throw a NullReferenceException
}
Alternative for View:
@{
var sessionVar = HttpContext.Currrent.Session["key"]; // assuming correct reference to Session["key"]
}
Controller:
Public ActionResult someMethod()
{
var sessionVar = System.Web.HttpContext.Current.Session["key"];
}