问题
I am trying to access view-state in client side but following exception coming :

JAVASCRIPT:
<script language="javascript" type="text/javascript">
var vCode = '<%=ViewState("code")%>';
alert(dateView);
</script>
CODE BEHIND:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ViewState("code") = "EE"
End Sub
Anybody suggest me how to do it?
回答1:
I would suggests to use RegisterHiddenField than mixing server/js codes:
You may try this sample:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ViewState("code") = "EE"
Page.ClientScript.RegisterHiddenField("vCode", ViewState("code"))
End Sub
On your javascript:
var vCode = document.getElementById("vCode");
alert(vCode);
回答2:
You can simply access the hidden form element that holds the viewstate.
The name of the control is __viewstate
.
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="..." />
var vCode = documents.forms[0]['__VIEWSTATE'].Value;
alert(dateView);
Of course, this will give you the encrypted/encoded/compressed viewstate.
If you want specific values from it, you may find it better to record them in hidden fields and access those.
回答3:
The Page.ClientScript.RegisterHiddenField did not work for me and returned null. You can do like this:
1-First solution: define a hidden field and make sure you set runat=server
<input type="hidden" id="myhiddenField" runat="server" value="" />
then in your code behind assign any value you want to it
myhiddenField.Value= ViewState["name"].ToString();// or assign any value you want
in your javascript access it like this:
<script type="text/javascript">
function test()
{
var name = document.getElementById('myhiddenField').value;
alert(name)
}
</script>
2-Second solution
In case for some reasons you don't want to have a server input control you can put the hidden field in a literal tag
<asp:literal id="literal1" runat="server"><input type="hidden" id="myhiddenField" value="{0}"/></asp:literal>
and then assign a value to the literal in codebehind like this
literal1.Text = string.Format(literal1.Text, "somevalue"); // somevlue can be your ViewState value
then access it in javascript as usual
var name = document.getElementById('myhiddenField').value;
alert(name)
Note: if you are using update panels put the hiddenfields inside the contenttemplate tag of the updatepanel
来源:https://stackoverflow.com/questions/6980714/how-to-access-viewstate-using-javascript