Gaff
Gaff

Reputation: 5667

How do you access an asp.net code behind session object member variable in javascript?

I have a class that handles all of my session variables in my asp.net application. Moreover, I sometimes store objects in the session variables so as to allow me to code very similar to a normal .net application.

For example, here is an object in a session variable:

public cUser User
{
    get { return (cUser)HttpContext.Current.Session["CurrentUser"]; }
    set { HttpContext.Current.Session["CurrentUser"] = value; }
}

And here is the instance of MySessionClass:

    public static MySessinClass Current
    {
        get
        {
            MySessionClass session = (MySessionClass)HttpContext.Current.Session["MySessionClass"];
            if (session == null) {
                session = new MySessionClass();
                HttpContext.Current.Session["MySessionClass"] = session;
            }
            return session;
        }
    }

So, in my code behind aspx page, I would just do something such as

int userID = MySessionClass.Current.User.UserID;

This works great and I love it. However, I want to apply the same principle in javascript from my aspx page:

var userID = <%=MySessionClass.Current.User.UserID%>;

However, when I access that webpage, I get an error saying that it does not recognize the MySessionClass object.

So, given the context that I am in, what would be the best way to reference that UserID variable, from the object, from the session, in javascript? Maybe my syntax to reference it is off or I am going at it the wrong way. Any help would be appreciated, thank you.

Upvotes: 0

Views: 4318

Answers (1)

x0n
x0n

Reputation: 52480

Since you've defined it as a static member, you would need to qualify your reference with the page type:

var userID = <%=MyPageType.MySessionClass.Current.User.UserID%>; 

That should be enough.

Upvotes: 3

Related Questions