Introduction
Any ASP.Net developer might have encountered the situation in which he wanted
to do a preprocessing on the client before the page is sent to the server. If you use LinkButtons for example ASP.Net renders the
__doPostBack
function
which handles the form dispatching. Even if you use the
Page.RegisterOnSubmitStatement
method to intercept the submission of the form you won't be
successful. If
the form is sent programmatically the OnSubmit
event is not fired. How to get between the whole thing? In Whidbey this might not occur anymore,
but Whidbey has not arrived yet. So here is a way to do it with .NET 1.1
Sample Scenario
To show you how it works I thought about the following scenario:
On the client you have a multiline textbox in which you want to enter html
code to send to the server. ASP.Net will not allow html code to be sent to the
server unless you use the page directive validateRequest = "false"
. This
is a global setting and I don't think to change this behavior is not a good idea.
In this case we can use submission-hijacking to escape the html code on the
client before it is sent to the server.
The following figure shows the error message produced by ASP.Net if you send
e.g. html code to the server:

Check out the sample below. You can see the textbox with the html code and a
LinkButton
to submit the information.

All you have to do to make it work is to put the following code in the
Page_Load
event.
Page.RegisterClientScriptBlock("ExcapeText",
"<script language="\""javascript\">\n" +
" // save the original function pointer of the .NET __doPostBack function\n" +
" // in a global variable netPostBack\n" +
" var netPostBack = __doPostBack;\n" +
" // replace __doPostBack with your own function\n" +
" __doPostBack = EscapeHtml;\n" +
" \n" +
" function EscapeHtml (eventTarget, eventArgument) \n" +
" {\n" +
" // execute your own code before the page is submitted\n" +
" document.all." + HtmlText.ClientID + ".value = escape(document.all."
+ HtmlText.ClientID + ".value);\n" +
" \n" +
" // call base functionality\n" +
" \n" +
" return netPostBack (eventTarget, eventArgument);\n" +
" }\n" +
"</script>\n");
This code injects a little JavaScript to do the preprocessing.
Let's get through the code:
1<script language="javascript">
2
3
4 var netPostBack = __doPostBack;
5
6 __doPostBack = EscapeHtml;
7 function EscapeHtml (eventTarget, eventArgument)
8 {
9
10 document.all." + HtmlText.ClientID +
".value = escape(document.all." + HtmlText.ClientID + ".value);
11
12 return netPostBack (eventTarget, eventArgument);
13 }
14</script>
In line 4 the function pointer of __doPostBack
is save in a global variable
netPostBack
. In line 6 a new function is assigned to the .Net function
__doPostBack
.
If ASP.Net calls its __doPostBack
function our EscapeHtml
function is
actually called. In line 10 the content of our textbox is escaped. In line 12
the original function is called through the reference saved in the variable
above.