I have inherited a .NET 4.0 application that uses some forms with buttons that call Oracle procedure. Often, before postback caused by pressing those buttons, RegisterStartupScript is used to show an alert after the execution, so after page refresh.
Now, I would like to disable re-submitting the form when the user presses F5 or refreshes the page, and I found that the most straightforward method is to use Response.Redirect to the same page instead of postback. So, I tried the following:
Protected Sub btnButton_Click(sender As Object, e As System.EventArgs) Handles btnButton.Click
Try
' Do something (call Oracle procedure)
Dim TheScript As New StringBuilder
TheScript.Append("<script language=JavaScript>alert(""Success!"");</script>")
ClientScript.RegisterStartupScript(GetType(String), "ShowInfoPage", TheScript.ToString)
Catch ex As Exception
' Do something
End Try
Response.Redirect(Request.Url.ToString(), False)
End Sub
but the alert (obviously) is not fired after page reload.
At this point I have two questions:
Thanks
The easiest methods are using a QueryString parameter or a Session to "store" that the event has been triggered.
The first snippet uses a QueryString:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Request.QueryString("status") = "success") Then
ScriptManager.RegisterStartupScript(Page, Page.GetType, "ShowInfoPage", "ShowInfoPage(1)", true)
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.Redirect(Request.RawUrl.ToString() + "?status=success", false);
End Sub
If you do not want a QueryString parameter to be visible you can use a Session:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not (Session("status")) Is Nothing) Then
If (Session("status").ToString = "success") Then
ScriptManager.RegisterStartupScript(Page, Page.GetType, "ShowInfoPage", "ShowInfoPage(2)", true)
Session.Remove("status")
End If
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Session("status") = "success"
Response.Redirect(Request.RawUrl.ToString, false)
End Sub
I used this code translator, so the VB code may not be 100% accurate.
You cannot prevent re-submitting the form when the user presses F5 or refreshes the page by default. This is just inherent behavior of browsing the internet. If this continues to be a problem you should maybe look into an Ajax solution?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With