In this article I will explain with an example, how to set Session variable using jQuery in ASP.Net using C# and VB.Net.
jQuery is a JavaScript library and JavaScript is a Client Side language and hence directly it is not possible to set Session variable in jQuery.
Thus, the solution is to make an AJAX call using jQuery AJAX and pass the value of JavaScript variable to a Web Method and inside the Web Method, the value will be set in Session variable in ASP.Net using C# and VB.Net .
HTML Markup
The HTML Markup consists of an ASP.Net TextBox and a HTML Button.
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.
Inside the Click event handler, an AJAX call is made to the SetSession WebMethod using jQuery AJAX and the value of the UserName TextBox is sent to the WebMethod.
The WebMethod then returns a string which is displayed using JavaScript Alert Message Box.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSet").click(function () {
$.ajax({
type: "POST",
url: "Default.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
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads