c# - Session is null when calling method from one controller to another...MVC -


i have asp.net mvc app , added new controller , call method new controller existing controller. using session variables , in controller call method in controller b:

if (session["grid"] != null){}//session object fine here       controllerb b  = new controllerb (); b.callmethod(); 

in new controller, i'm calling b, method looks this:

public object callmethod(){     if (session["grid"] != null)//session object null         {             //do thing         }   } 

the session variable isnt problem, session object. null, hence application blows up. session alive , in controller a, why null in controller b? thank you

that's because controllerb needs initializes itself, , part of process sets session, request, resposne etc accordingly.

so, need call initialize method , pass current requestcontext. but, since it's marked protected (because wasn't meant called directly, using controllerfactory), you'll have expose it:

public class controllerb : controller {     public void initializecontroller(requestcontext context)     {         base.initialize(context);     } } 

then in controllera:

var controllerb = new controllerb(); controllerb.initializecontroller(this.request.requestcontext); 

alternatively, since session getter shorthand this.controllercontext.httpcontext.session (same request, response etc), can set controllercontext instead:

var controllerb = new controllerb(); controllerb.controllercontext = new controllercontext(this.request.requestcontext, controllerb); 

see msdn


Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -