ASP.NET AJAX: Use PageMethods Proxy to Read and Write Session Data

Ever had the need to read or write a piece of session data from the browser?  Here is an example of an easy way this can be accomplished using ASP.NET AJAX.  The approach is pretty simple.  First, add a couple of static methods to the page for setting and retrieving the session value (SetSession and GetSession) as well as the ASP.NET AJAX ScriptManager control.  Then write the javascript code that calls the PageMethods proxy to invoke these methods on the server (in my simple example, I wired the onclick handlers of 2 buttons).

There only 2 details that are really worth mentioning.  The first is that the static methods need to be marked with the System.Web.Services.WebMethod attribute.  The second is that the EnablePageMethods attribute of the ScriptManager needs to be set to true so the ScriptManager will autogenerate the PageMethods proxy for us.  Thats it for the implementation details, but I should probably add a quick disclaimer that the sample below is just for demonstration - showing that it is possible to access the Session object from the client (and Application and Cache for that matter).  Obviously, you will need to deisgn the interface to it that best fits the needs of your application.  Whats that cheesy line from Spider Man again - oh yea

'With great power, comes great responibility' - Uncle Ben to Peter Parker     

Live Demo

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
    
    /// <summary>
    ///
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    [System.Web.Services.WebMethod]
    public static void SetSession(string key, string value)
    {
        HttpContext.Current.Session[key] = value;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    [System.Web.Services.WebMethod]
    public static string GetSession(string key)
    {
        return (string)HttpContext.Current.Session[key];
    }
    
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        //  JavaScript callback that is invoked when
        //  the method call returns
        function ScriptCallback(result)
        {
            $get('txtSessionKey1').value = result;
        }
    </script>
</head>
<body>
    <form id="frm" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />

        <table>
            <tr>
                <td colspan="3">
                    <div style="background-color:AliceBlue">
                        An example of reading and writing session data from the client<br />
                        using the PageMethods proxy generated by the ScriptManager<br />
                        To test, enter a value in the text box and click the 'Update' button<br />
                        This will write the value to session state on the server using the PageMethods<br />
                        proxy.  Then try refreshing the page and clicking the 'Fetch' button.<br />
                    </div>
                    <br />                
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label runat="server" Text="SessionKey1" />
                </td>
                <td>
                    <input id="txtSessionKey1" type="text" />
                </td>
                <td>
                    <asp:Button 
                        runat="server" Text="Fetch" 
                        OnClientClick="PageMethods.GetSession('SessionKey1', ScriptCallback); return false;" />
                    
                    <asp:Button 
                        runat="server" Text="Update" 
                        OnClientClick="PageMethods.SetSession('SessionKey1', txtSessionKey1.value); return false;" />
                </td>
            </tr>            
        </table>
    </form>
</body>
</html>


 


TrackBack

TrackBack URL for this entry:
http://mattberseth.com/blog-mt/mt-tb.fcgi/34

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)