In this article I will explain with an example, how to persist JavaScript variables and objects across PostBack in ASP.Net.
 
 

HTML Markup

The HTML Markup consists of following controls and elements:

Controls

Button – For updating the JavaScript Array.
The Button has been assigned with an OnClientClick event handler.
 

Elements

SPAN – For displaying preserved values.
HiddenField – For storing values.
C#
<span id="array_display"></span
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="UpdateArray()" /> 
<input type="hidden" id="array_store" name="ArrayStore" value='<%=this.ArrayStore %>' /> 
 
VB.Net
<span id="array_display"></span
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="UpdateArray()" /> 
<input type="hidden" id="array_store" name="ArrayStore" value='<%= Me.ArrayStore %>' /> 
 
 

Persisting JavaScript variables and objects across PostBack

First, the variable is declared.
Inside the JavaScript window.onload event handler, the contents of the HiddenField is displayed in HTML SPAN.

UpdateArray

When the Submit Button is clicked, the JavaScript UpdateArray function is called. Then, a variable is created and a check is performed if Array is empty. If found empty, then a new Array object is created if not empty, then it is separated by comma (,).
After that, the push method is called where an Array is passed with adding 1 as parameter to it.
The join method is called where we pass comma (,) to it and then, it stored inside the value.
<script type="text/javascript">
    var array_store;
     window.onload = function () {
        array_store document.getElementById("array_store");
        document.getElementById("array_display").innerHTML array_store.value;
    };
    function UpdateArray() {
        var arr;
        if (array_store.value == "") {
            arr = new Array();
         } else {
            arr array_store.value.split(",");
        }
        arr.push((arr.length + 1).toString());
        array_store.value arr.join(",");
    };
</script>
 
 

Updating Array using C# and VB.Net

First the string variable is created and empty value is stored inside it.
Inside the Page_Load event handler, the value of HiddenField is fetched from the Request.Form collection and set in the variable (created earlier).
C#
protected string ArrayStore "";
protected void Page_Load(object sender, EventArgs e)
{
    this.ArrayStore Request.Form["ArrayStore"];
}
 
VB.Net
Protected ArrayStore As String ""
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
    Me.ArrayStore Request.Form("ArrayStore")
End Sub
 
 

Screenshot

Persist JavaScript variables and objects across PostBack in ASP.Net
 
 

Browser Compatibility

The above code has been tested in the following browsers.
Microsoft Edge   FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Demo

 
 

Downloads