Using PageMethods to access Session data

There are two C# methods in the page. One overrides the the OnLoad method and stores a value in session state for demonstration purposes. The other is a static method decorated with the WebMethod attribute that can be called from JavaScript. It retrieves the value for the given key from session state. Currently, only static methods are callable use the PageMethods object in the browser.
In the JavaScript code, there is a pageLoad method which will be called automatically by the ASP.NET AJAX script library. The PageMethods object is used to invoke the method on the server. It provides callbacks for success and error. The success callback just displays the value retrieved from session state on the server.

 <%@ Import Namespace=”System.Web.Services” %>
<script runat=”server” language=”C#”>
protected override void OnLoad(EventArgs e) {
    HttpContext.Current.Session[“foo”] = “bar”;
}

[WebMethod]
public static string Session(string key) {
    return (string)HttpContext.Current.Session[key];
}
</script>script type=”text/javascript”>
function
pageLoad(sender, arg) {
    PageMethods.Session(
“foo”, OnCallComplete, OnCallError);
}
function OnCallComplete(result, userContext, methodName) {
    alert(result);
}
function OnCallError(error, userContext, methodName) {
    if(error !== null) {
        alert(error.get_message());
    }
}
</script>
<
form runat=”server”>
<asp:scriptmanager runat=”server” id=”scriptmanager” />
</
form>

(sursa: http://blogs.msdn.com/mattgi)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s