In this article I will explain with an example, how to use
Session inside
WebMethod in
ASP.Net using C# and VB.Net.
HTML Markup
The
HTML Markup consists of:
TextBox – For capturing username.
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnSet" type="button" value="Set Session" />
Sending the value of variable to WebMethod using jQuery AJAX
The
Set Button has been assigned a
jQuery Click event handler.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSet").click(function () {
$.ajax({
type:"POST",
url: "CS.aspx/SetSession",
data: '{name: "' + $("[id*=txtUserName]").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
Server Side Web Method
Inside the
SetSession WebMethod, the value sent from the Client Side is received as parameter and is set into the
Session variable.
Finally, the value is read back from the
Session variable and sent back to the Client along with Current Server’s Date and Time in string format.
Note: The method is declared as
static (C#) and
Shared (VB.Net) and also it is declared as
WebMethod unless you do this you won’t be able to call the methods.
C#
[System.Web.Services.WebMethod]
public static string SetSession(string name)
{
HttpContext.Current.Session["Name"] = name;
return "Hello " + HttpContext.Current.Session["Name"] + Environment.NewLine + "The Current Time is: " + DateTime.Now.ToString();
}
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function SetSession(ByVal name As String) As String
HttpContext.Current.Session("Name") = name
Return "Hello " & HttpContext.Current.Session("Name") & Environment.NewLine & "The Current Time is: " & DateTime.Now.ToString()
End Function
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads