Thursday, January 26, 2012

Invalid Viewstate w/ ASP.Net Cross-page Posting

Recently, I had a need to send data from one page to another as part of preview functionality for a web-app. Various factors made it best to send this data as a POST rather than attaching it to as a querystring to send via GET. In every web development environment I worked in prior to ASP.Net, this is as simple as changing the action associated with the form that sends the data (so that it points to the other page instead of posting to itself. The receiving page processes the POST data from an alternate page the same way it would process the POST data from itself (assuming, of course, that you aren't using a form filled with ASP controls, in which case it does get more complicated...*).

When I tried to implement this same model in ASP.Net, it failed, producing a server run-time error stating that the Viewstate of the receiving page was invalid (and explicitly not referencing any of my code). Lovely. After digging in a bit further, it was an easy fix. It turns out that the action on the form needs to remain the source page itself. There are special attributes you can include on an ASP.Net control button which tell the button to act as a submit button targeting a different page than the normal form action. So the fix was as simple as replacing my HTML submit button with this ASP.Net control:

<asp:Button runat="server" PostBackUrl="page.aspx" ID="btnID" Text="Submit"/>

That's a simple solution, and with it in place, everything else seems to work as expected. Regardless, I find it annoying that breaking a basic functionality of HTML is somehow deemed acceptable in ASP.Net, so long as they provide this work-around.

* The more complicated part of dealing with ASP.Net controls is only slightly more complicated. Your current page doesn't have these controls in the Viewstate as it would with a typical ASP.Net postback. Instead, these controls are loaded into a PreviousPage object, which you then reference via PreviousPage.FindControl("id").

No comments:

Post a Comment