Reputation: 167
Page 1 has the flowing code logic when pressing a button
If MyDataIsValid() Then
ScriptManager.RegisterStartupScript(me, me.GetType(), "PopUp", "", False)
Response.Redirect("~/Page2", false)
Else
ScriptManager.RegisterStartupScript(me, me.GetType(), "PopUp", <some js for a popup>, False)
End If
If the fist time I press the button and the data is not valid then then popup will show. The second time I use valid data and the page redirects to Page2. If I navigate backwards by pressing the back button on the browser, the popup will show. That's the problem, the popup will falsely tell me my data is not correct.
I know I can make a button on Page2 to redirect me to Page1 but I also want the back button of the browser to work correctly.
When navigating backwards using the browser back button the Load event in Page1 does not run. The page loads the cached page of the first time I press the button.
I tried
Response.Cache.SetCacheability(HttpCacheability.NoCache)
or the
Response.Buffer = true
Response.CacheControl = "no-cache"
Response.AddHeader("Pragma", "no-cache")
Response.Expires = -1441
so the page will no cache but it dos not work. The page does not reload at back button from the browser.
Upvotes: 1
Views: 379
Reputation: 2685
This is your solution: Setting your script to Blank/Nothing before you redirect routes to another page.
Private Sub WebForm1_PreLoad(sender As Object, e As EventArgs) Handles Me.PreLoad
If Session.Item("Script") IsNot Nothing Then
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "PopUp", "<script type='text/javascript'>" & CStr(Session.Item("Script")) & "</script>", False)
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If MyDataIsValid() Then
Session.Item("Script") = ""
Response.Redirect("~/Page2.aspx")
Else
Session.Item("Script") = "alert('Script is running')"
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "PopUp", "<script type='text/javascript'>" & CStr(Session.Item("Script")) & "</script>", False)
End If
End Sub
To avoid cached pages by browser work on it history by Javascript (client side) as follows.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If MyDataIsValid() Then
Session.Item("Script") = ""
Response.Redirect("~/Page2.aspx")
Else
Dim sbScript As StringBuilder = New StringBuilder()
sbScript.AppendLine("( function () { window.history.pushState(window.history.state, " &
" 'Not allowed', " &
" 'https://yourdomain.com/page2.aspx'); }()); ")
ScriptManager.RegisterStartupScript(Me,
Me.GetType(),
"PopUp",
"<script type='text/javascript'>" & sbScript.ToString & "</script>",
False)
End If
End Sub
However make all control validation by Javascript if it is possible as Client side have more control on Browser than Server side
Upvotes: 1