11

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

user3853187
  • 127
  • 1
  • 1
  • 5

1 Answers1

11

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".

Moshtaf
  • 4,833
  • 2
  • 24
  • 34
  • Is it not possible to directly use them , the way we use them in server side? – user3853187 Aug 05 '14 at 19:53
  • It's possible but not in a clean way.All `ViewState`s 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: `__VIEWSTATE`. – Moshtaf Aug 05 '14 at 19:57
  • No there is no way like server-side one. – Moshtaf Aug 05 '14 at 19:58
  • and what about session state variables? – user3853187 Aug 05 '14 at 20:01
  • For sessions just simply use `alert('<% = Session("sessionName") %>');` in VB and `alert('<% = Session["sessionName"] %>');` in C. – Moshtaf Aug 05 '14 at 20:05