Search code examples
javascriptjqueryasp.netviewstate

How to access ViewState variable in Client side Javascript or JQuery


Is this possible to access ViewState variable at Client Side javascript or jquery functions in asp.net web application? If yes then how?


Solution

  • First Solution:

    You can pass any variable from codebehind to client-side using properties. Define a Public propery in codebehind:

    C#:

    public int prtPropertyName {
        get { return ViewState("PropertyName"); }
        set { ViewState("PropertyName") = value; }
    }
    


    VB:

    Public Property prtPropertyName As Integer
        Get
            Return ViewState("PropertyName")
        End Get
        Set(value As Integer)
            ViewState("PropertyName") = value
        End Set
    End Property
    

    assign a value to the property and then get the value in javascript using this:

    <% = prtPropertyName  %>
    


    Second Solution:

    Put the ViewState's value in a hidden field and read the hidden field value in client-side:

    ViewState("viewStateName") = "This is ViewState value"
    Page.ClientScript.RegisterHiddenField("hfHiddenFieldID", ViewState("viewStateName"))
    

    Javascript:

    var strValue = document.getElementById("hfHiddenFieldID");
    


    Third Solution:

    This one is not so clear but all ViewStates is saved in a hidden field that created by ASP.NET automatically, you can find the field and read data. You can find this fields in source code of page with this name and id: name="__VIEWSTATE" id="__VIEWSTATE".