Access session on view page in ASP.Net MVC

2019-07-18 09:05发布

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.

标签: asp.net razor
2条回答
We Are One
2楼-- · 2019-07-18 09:37

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. :)

查看更多
我命由我不由天
3楼-- · 2019-07-18 09:47

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:

  1. Session["key"] is null.
  2. 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"];
}
查看更多
登录 后发表回答