PDA

View Full Version : استفاده از PageMethods برای دسترسی به Session



Vahid_moghaddam
شنبه 28 اردیبهشت 1387, 13:52 عصر
<%@ 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" EnablePageMethods="true" />
</form>

Vahid_moghaddam
شنبه 28 اردیبهشت 1387, 14:28 عصر
خواندن Session و نوشتن در آن:


<%@ 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>
<input id="txtSessionKey1" type="text" />
<input type="submit" name="ctl03" value="Fetch" onclick="PageMethods.GetSession('SessionKey1', ScriptCallback); return false;" />

<input type="submit" name="ctl04" value="Update" onclick="PageMethods.SetSession('SessionKey1', txtSessionKey1.value); return false;" />

</body>
</html>