Hi moquamar,
Refer below example.
HTML
C#
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGet" type="button" value="Get Session" onclick="GetSession()" />
<script type="text/javascript">
window.onload = function () {
'<% var MyVar = "123";
Session["Data"] = MyVar; %>';
}
function GetSession() {
var name = document.getElementById("<%=txtUserName.ClientID%>").value;
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request != null) {
var url = "Default.aspx/GetSession";
request.open("POST", url, false);
var params = "{name: '" + name + "'}";
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(JSON.parse(request.responseText).d);
}
};
request.send(params);
}
}
</script>
VB.Net
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGet" type="button" value="Get Session" onclick="GetSession()" />
<script type="text/javascript">
window.onload = function () {
'<% Dim MyVar = "123"
Session("Data") = MyVar %>';
}
function GetSession() {
var name = document.getElementById("<%=txtUserName.ClientID%>").value;
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request != null) {
var url = "Default.aspx/GetSession";
request.open("POST", url, false);
var params = "{name: '" + name + "'}";
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(JSON.parse(request.responseText).d);
}
};
request.send(params);
}
}
</script>
Code
C#
[System.Web.Services.WebMethod]
public static string GetSession(string name)
{
return "Hello " + name + Environment.NewLine + "Session value is : " + HttpContext.Current.Session["Data"];
}
VB.Net
<System.Web.Services.WebMethod>
Public Shared Function GetSession(ByVal name As String) As String
Return "Hello " & name & Environment.NewLine & "Session value is : " & HttpContext.Current.Session("Data")
End Function
Screenshot