In this article I will explain with an example, how to use ViewState variable inside JavaScript in ASP.Net with C# and VB.Net.
ViewState is a Server Side class object which though stores the data on Client Side but it is in Encrypted Form (Hashed format) and hence cannot be read by Plain JavaScript.
Thus the ViewState variable is accessed inside JavaScript code with the help of Server Side Code Blocks in ASP.Net with C# and VB.Net.
 
 
Setting the ViewState object on Server Side in ASP.Net
Inside the Page Load event, the ViewState object is set with a String value.
C#
protected void Page_Load(object sender, EventArgs e)
{
    ViewState["Message"] = "Hello Mudassar";
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    ViewState("Message") = "Hello Mudassar"
End Sub
 
 
Accessing ViewState object inside JavaScript in ASP.Net
The ViewState variable is accessed with the help of Server Side Code Blocks (<% %>) in JavaScript and the String value is displayed using JavaScript Alert Message Box.
C#
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <script type="text/javascript">
        var message = '<%=ViewState["Message"].ToString() %>';
        alert(message);
    </script>
    </form>
</body>
</html>
 
VB.Net
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <script type="text/javascript">
        var message = '<%=ViewState("Message").ToString() %>';
        alert(message);
    </script>
    </form>
</body>
</html>
 
 
Screenshot
Using ViewState inside JavaScript in ASP.Net
 
 
Demo
 
 
Downloads