Preventing Postbacks on the Client Side

Have you ever had the desire to prevent a form from posting back if certain conditions were met on a form? Suitable reasons would be for pages that send a large amount of data to/from the server on postback.  My first thought was that this could be handled by adding an OnSubmit to the form tag using the Form.Attributes.Add() method, but I found that whatever I added through codebehind was put in execution order AFTER the submit method.

To get around this, first we need some client side scripting for validation:

<script language=”javascript”>
function clientValidation()
{
//put code to grab some information from your form here
var textValue = String(FormName.FormBox.value).toLowerCase();

if (textValue.lastIndexOf(“failure value“)!=-1)
{return false;}
else {return true;}  
}

The rest of the solution hinges on the way ASP.NET creates postbacks.  It inserts a client side script called “__doPostBack” to submit the form.  To circumvent, since javascript var's can hold just about anything, we'll replace __doPostBack with a slightly modified version:

if (document.all)
{
if (window.__doPostBack)  //if __doPostBack exists
__doPostBack = function(eventTarget, eventArgument) //hijack the function
{
if (clientValidation())
{

//MS's __doPostBack body:
var thisForm = document.FormName;
thisForm.__EVENTTARGET.value=eventTarget;
thisForm.__EVENTARGUMENT.value=eventArgument;
document.FormName.submit();

}
else //we'll just alert here instead of submitting.
{alert(”Textbox's value cannot be 'failure value'”);}
}}
</script>

And that's all there is to it.  Now you don't have to wait for the whole page to be sent up just to find out that your server validation method returned false. 

1 Comment

Comments have been disabled for this content.