0

A session is being passed after successful login from a aspx page to an html page, i want to be able to get the session object using JSON and modify html elements, can anyone post a simple example on how to do that using JSON ?

thanks.

2
  • can you please elaborate on your request, maybe even add a code snippet of what you thing it would look like? Commented Jan 25, 2012 at 10:18
  • Let me try to rephrase your question. You would like to get all the user session variables serialized as JSON available in the clientside using JavaScript? Commented Jan 25, 2012 at 10:19

2 Answers 2

1

You will need to make a AJAX call from the clientside to a web service method or a page method (webmethod defined in your page).

If you choose for the page method option your code could be something like this:

Your code behind of your Page.aspx

    public class CustomSessionObject
    {
        public string Name { get; set; }
    }

    [WebMethod]
    public static object GetSessionData()
    {
        try
        {
            return HttpContext.Current.Session["THE_SESSION_VAR_YOU_NEED"] as CustomSessionObject;
        }
        catch (Exception e)
        {
           //Log Exception

            throw;
        }
    }

I would not advise to always give back all the session vars. Make it explicit and give only back the ones you need. This way if on a later moment in time a other developer adds more user session vars they will not be returned as well. If you do this, it might be a security leak in the future.

Using JQuery for making the AJAX call.

var handleError = function(jqXHR, textStatus, errorThrown) {
    alert("An error occurred: " + jqXHR.responseText);
};

var handleSuccess = function(data, textStatus, jqXHR) {
    if (data && data.d) {
        alert(data.d.Name);
    }
};

$.ajax({
    url: 'Page.aspx/GetSessionData',
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: handleSuccess,
    error: handleErr
});

Also read this for some more info.

Sign up to request clarification or add additional context in comments.

Comments

0

The Session object is usually server-side, referenced using a session key stored in a client cookie.

Also, JSON is a data transfer format, so it doesn't really do anything. Perhaps you mean jQuery?

If you want to be able to modify it at the client and at the server, you want client cookies. Read this overview: http://msdn.microsoft.com/en-us/library/ie/ms178194.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.