1

I hava 2 controllers: ControllerA and ControllerB, and set value for session in controllerA, but can't get value in ControllerB, code like:

public class ControllerA : Controller
{
    public ActionResult Index()
    {
        Session["a"] = "test";
    }
}

public class ControllerB : Controller
{
    public ActionResult Index()
    {
        ViewBag.Test = Session["a"].ToString();
    }
}

I tried use cookie to instead of session, but has same problem. I don't know if I should use session in C# MVC, please let me know if something is better then session. Thank you.

Mike
  • 565
  • 1
  • 4
  • 5

3 Answers3

1

It could be an issue with the SystemIdleTime variable in the IIS. Request your hosting provider to increase this value to 30 minutes or 0 for no-timeout.

You could check this article

Also check my similar question that I posted few days back

Community
  • 1
  • 1
Sujoy
  • 1,051
  • 13
  • 26
0

First create SessionController.cs

public class SessionController
{

    const string sessionname = "UserContext";
    public static SessionDetail UserContext
    {
        get
        {
            return System.Web.HttpContext.Current.Session[sessionname] as SessionDetail;
        }
        set
        {
            HttpContext.Current.Session[sessionname] = value;
        }
    }

}
 public class SessionDetail
 {
      public string Employee_ID { get; set; }
 }

Inherits this controller to any other controller where Session is use

for example :

public class DashboardController : SessionController
{
    SessionController.UserContext.Employee_ID = "1";//Assign Value
    var empId =   SessionController.UserContext.Employee_ID; //Use Value
    ....
}

Then Add this code to Global.asax

protected void Session_Start()
{
     SessionDetail sdetail = new SessionDetail();
     SessionController.UserContext = sdetail;
}
ujval
  • 51
  • 1
  • 3
0

Before getting value from session you should set the value for the session, try to execute index method of controller A and then try to execute controller B, it'll work or else dibug the execution you'll get the excat problem

And for communicating between controller you cab use tempdata instead of sessions

Amy
  • 35
  • 12