How to fix AutoPostBack and PostBack error for ASP.NET pages with PostBackUrl button
I recently worked on a web page which used the new PostBackUrl feature for buttons. On the same page I used an RadioButtonList with AutoPostBack enabled. After testing the page something strange happened in FireFox. When I clicked on an item in the RadioButtonList I was sent to the PostBackUrl page. After some debugging and testing the same page both in FireFox and Internet Explorer I found what was wrong.
When you click on a button with a PostBackUrl, the ASP.NET JavaScript changes the page's form action attribute to the PostBackUrl. When the you go back to the previous page by clicking on the browser's back button, the AutoPostBack on that page is now broken. This also breaks the normal postback for buttons with no value for PostBackUrl. FireFox remembers the page's last state and in this case that the action attribute is set to the PostBackUrl. This is not a problem in Internet Explorer, it doesn't remember it's state when going back. The problem only occurs when the user clicks on the back button or on a JavaScript link which will cause the browser to go back.
The problem is the way __doPostBack works. It relies on the action attribute of the page's form. Whatever action is set to. Of course it's possible to fix this in several ways. If you want you can try to change it on the server side. But it's really not necessary. A few lines of JavaScript will do the trick.
Solution
Put this little piece of code directly after the <form runat="server"> on your page.
| ASP.NET |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<form id="form1" runat="server">
<script type="text/javascript">
// PostBackUrl hack by Per Zimmerman | www.dentaku.com
var __oldAction = theForm.action;
var __oldPostBack = __doPostBack;
__doPostBack = function(eventTarget, eventArgument) {
theForm.action = __oldAction;
__oldPostBack(eventTarget, eventArgument);
}
</script>
<!-- rest of the page... -->
</form>
|
You can put it anywhere after the form, but it's better that the code is run as soon as possible. The first time the page is loaded, the code stores the original action and postback function in variables and then sets __doPostBack to a new function. When the new __doPostBack is called it first resets the action attibute to the original value before it calls the old __doPostBack function. You could set action attibute to an empty string to get a normal postback, but I wanted to make sure the function use the value ASP.NET supplied.
Test pages
I've uploaded test pages for you to try.
- Default page
- Hacked page
2006-06-03 23:11:00 | Posted in
ASP.NET
| Link | digg this