In this article I will explain with an example, how to use ViewState inside Static WebMethod in ASP.Net using C# and VB.Net.
ViewState is an ASP.Net State management technique in which the state (data) is maintained on Page across PostBack.
ViewState is not accessible inside Static WebMethod and hence Session or Cache state management techniques can be used in ASP.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