Article

How To Use ViewState inside JavaScript in Asp.Net

Here Laxmikant has explained with an example, How To Use ViewState inside JavaScript in Asp.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.
It is a Page-Level State Management technique. View State is turned on by default and normally serializes the data in every control on the page regardless of whether it is actually used during a post-back.

Thus the ViewState variable is accessed inside JavaScript code with the help of Server Side Code Blocks in ASP.Net with C#.

In this article we will learn with an example, How To Use ViewState inside JavaScript in Asp.Net C#.

ViewState does not hold the controls, it holds the values of controls. It does not restore the value to control after page post back.

Step 1: Now create the project as:
“Start” –> “All Programs”- “Microsoft Visual Studio 2012”.
“File” – “New Project” – “C#” – “Empty Project” (to avoid adding a master page).
Give the Project name such as ViewStateExample or another as you wish and specify the location.
Then right-click on Solution Explorer – “Add New Item” – “WebForm1.aspx” page.

Step 2:Open WebForm1.aspx page and write this code.

Note: Accessing ViewState object inside JavaScript in ASP.Net.
You can see The ViewState variable is accessing with the help of Server Side Code Blocks (<% %>) in JavaScript and the String value is displayed using Alert Message Box.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="VewStateExample.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        var msg = '<%=ViewState["Msg"].ToString()%>';
        alert(msg);
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>

Step 3: Open “WebForm.aspx.cs” page and write this code on page load.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace VewStateExample
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           //You can see Inside the Page Load event, the ViewState object is set with a String value.
             ViewState["Msg"] = "Welcome To LanguageTechFunda";

        }
    }
}

Screenshot
use-viewstate-inside-javascript-asp-net

Leave a Reply

Your email address will not be published. Required fields are marked *