Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent exceptions from half-loaded pages' form submission while using asp.net event validation?

I have a page with some dynamically added buttons. If you click a button before the page has fully loaded, it throws the classic exception:

Invalid postback or callback argument. 
Event validation is enabled using in configuration or in a page. For

security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

I am guessing the Viewstate field hasn't loaded on the form yet, the the other bits are being submitted. What's the best way to prevent this error, while maintaining Event Validation?

like image 550
Shawn Avatar asked Oct 31 '08 17:10

Shawn


2 Answers

I answered a similar question here. To quote:

Essentially, you'll want to get the ViewState to load at the top of the page. In .NET 3.5 SP1 the RenderAllHiddenFieldsAtTopOfForm property was added to the PagesSection configuration.

Web.config

<configuration>

    <system.web>

        <pages renderAllHiddenFieldsAtTopOfForm="true"></pages>

    </system.web>

</configuration>

Interestingly, the default value of this is true. So, in essence, if you are using .NET 3.5 SP1 then the ViewState is automatically being rendered at the top of the form (before the rest of the page is loaded) thus eliminating the ViewState error you are getting.

like image 120
Jeffrey Harrington Avatar answered Nov 02 '22 20:11

Jeffrey Harrington


I've found this to be caused more often by the __EVENTVALIDATION field than the ViewState not being loaded. The __EVENTVALIDATION is at the bottom of the page and if it hasn't been received by the client when the user causes a postback you will get that exception.

I've not yet found a great solution, but what I usually do on pages that tend to cause this due to large amounts of content is to wire up the buttons to a javascript function that checks an isLoaded var that only gets set to true in the document.ready call. If isLoaded is false it silently eats the event, if it's true it lets if go through. This is a pain to set up, but it has ended most of my invalid postback issues.

like image 2
Andy C. Avatar answered Nov 02 '22 19:11

Andy C.