My Books recommendations

Wednesday, June 10, 2009

How to pass session variable in sharepoint webpart


During  my current project I came across this small hiccup, where I wanted to pass value of a variable from one page to the other in a sharepoint webpart, since Webpart doesn’t provide this out of the box. I have discovered this little gem from my research.


I wanted to retain value of logged in user’s style preference for the page, the following line of code besically retains the value in the combination of page session and and class variable.


strUser = loggedInUser [strUser declared at class level]


                  Page.Session.Add("userStyle", strUser); //when user first time login/load on the page.


      Then use this Page.Session object to retrive the value of strUser for other functions like:


strUser = Page.Session["userStyle"].ToString();


and write the value of the strUser using


Page.Response.Write("StrUser:" + strUser);




Hope this helps.


jeymal said...

Hi Nilesh,
i tried using session variables,but the session variables expires when we redirect to next page.Can u give me a solution for it...

Nilesh Vasave said...

Have you enabled session state in the web application's web.config file?

These are the 3 values which is set in my web.config file.

< add name="Session" type="System.Web.SessionState.SessionStateModule" />

< pages enableSessionState="true" enableViewState="true" enableViewStateMac="true" validateRequest="false" pageParserFilterType="Microsoft.SharePoint.ApplicationRuntime.SPPageParserFilter, Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" asyncTimeout="7">

< sessionState mode="SQLServer" timeout="60" allowCustomSqlDatabase="true" partitionResolverType="Microsoft.Office.Server.Administration.SqlSessionStateResolver, Microsoft.Office.Server, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />"

jeymal said...

Thanks for the reply..yes i have enabled the session as you told in web config file but the session mode i want to use "InProc" as we can use state server and sql server only for web Farm or web garden.My application is small and cannot use sqlserver or state server mode...

Nilesh Vasave said...

I just remember another setting, you also need to initialise the sessions in application's global.asax page in onsessionstart

protected void Session_Start(object sender, EventArgs e)
Session.Add("Session1", "");


jeymal said...

Hats off to you buddy..First of all thank you a lot as i got a good breakthrough in my R&D regarding session variables which am trying for the past 45 whatever i hardcode in the Session event i can get it in all pages...but if i assign a value to session object i cant get the value in the redirecting page (can get the value only in the assigned)...anyway thanks..i will any workaround to get it..take care dude..