Friday, December 19, 2008

ASP.NET: Loading Session Variable at Client Side

MOSS 2007 does not allow in-line code and one may require printing session variables in between HTML. Some time one require printing session variable in HTML which is content in Web Part. I started applying different approaches.

Parse Content in Content Editor Web part
First I thought to inherit Content Editor Web Part and Parse the HTML. During parsing and replace special marker with session variable name with actual values. e.g. In HTML write variable name like Your Name : $$SesstionVariableName$$
Unfortunately Content Editor Web part is sealed class so you cannot inherit. Here you feel like you cannot do anything now or write your own content editor web part. But, wait is it good idea to edit Content inside content editor web part at server side?

Play with Java Script and HTML
Idea is to load required session variable in Java Script variable and traverse the DOM to find session marker. Session markers? Yes, hidden inputs as session marker. Let’s take an example, let's say I have session variable named “UserName”. I want this variable to be loaded in between some HTML paragraph
form id="form1" runat="server">
<div>Your Name is <input type="hidden" name="test" value="$$$$"

Logic to create an array of required session variables in Java Script. We have to tell, what are the session variable names. For that let’s create User Control. Property of User Control will specify the name of session variable as comma separated values. Code behind will load this session variables in Java Script Array.
Something like
var MultiArray = new Object MultiArray['" + sessionvariable + "'] = '" + Session[sessionvariable].ToString () + "';

So far ok. We have session variable at client side now how to find hidden variable in HTML and replace with session values. Let's traverse the DOM and track for HIDDEN input. Once you find it check the name and values. If values is ‘$$$$’ means it is session variable so get the name and find from the array and replace INPUT tag with value.

Here we go! This is just concept. Code is very basic and need correction and runtime error checking. Feel free to use and extend.
Post a Comment