cpradio's tidbits of information a one stop spot for my personal references

20Aug/07Off

ViewState, is it working properly?

Today, Aaron and I were wondering if ViewState actually works properly in .NET. For example, in .NET you have the option to disable ViewState in the web.config file, the page directive, or on each control individually. However, using any of the three methods or any combination continuously results in "__VIEWSTATE" appearing as a hidden field in the form!

The problem gets worse when you try to submit the form to another page by overriding the form's action. This throws an "ViewState is corrupt or invalid for this page." error. We finally got around it by hacking a JavaScript event to empty the "__VIEWSTATE" hidden field so it had nothing in it before the form actually submitted the page. But is that the only way to get rid of ViewState?

Code to cause ViewState corruption:

<script type="text/javascript">
    window.onload = function()
    {
        document.getElementById('Form1').onsubmit = function()
        {
            document.getElementById('Form1').action = '/another_project/another_page.aspx';
        }
    }
</script>

How, we got around it:

<script type="text/javascript">
    window.onload = function()
    {
        document.getElementById('Form1').onsubmit = function()
        {
            var inputFields = document.getElementsByTagName('input');
            for (var i = 0; i < inputFields.length; i++)
            {
                if (inputFields[i].name.toUpperCase() == "__VIEWSTATE")
                {
                    inputFields[i].value = ""; // Empty the ViewState hidden field to stop it from carrying on to the next page
                    break;
                }
            }

            document.getElementById('Form1').action = '/another_project/another_page.aspx';
        }
    }
</script>

Anyone else have a problem like this?

Filed under: .NET, Code, Work Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.