VB.NET - Page.RegisterStartupScript Problem

Asked By Blair Yumi
10-May-11 11:09 PM
This code is what I use to redirect a page using javascript, and this is how I execute it in VB

Page.RegisterStartupScript("SCRIPTNAME", "<script language='javascript'>ConfirmSave();</script>")



It work properly, but whtn I presse the back button in IE of the redirected page back to my main page, the confirm box reappear, the one that the function ConfirmSave() does.

Please help me on being able to not execute again the function when I press the back button Please. Thanks
  Vickey F replied to Blair Yumi
10-May-11 11:12 PM
When you press back button then browser again show previous output, because of that you are getting same page with dialog,

to solve this problem clear the history-

I provide you with solutions to disable back function in your web page as below:

1.Disable the page cache using script on server-side. The code is as below:

   Response.Buffer = true;
   Response.ExpiresAbsolute = DateTime.Now.AddHours(-1);
   Response.Expires = 0;
   Response.CacheControl = "no-cache";

 

2.Disable the page cache to let the browser no longer save cache of web pages on client-side as below:

   <head>  
    <meta http-equiv="Expires" CONTENT="0">  
    <meta http-equiv="Cache-Control" CONTENT="no-cache">  
    <meta http-equiv="Pragma" CONTENT="no-cache">  
   </head>

 

3.Use javascript on client-side to realize the forward effect, this counteracts the action of user’s clicking back button. See the code below:

   <script type="text/javascript">  
    window.history.forward(1);  
   </script>

 


try this code.

  James H replied to Blair Yumi
10-May-11 11:13 PM
Emits a client-side script block in the page response.
The following code example demonstrates the use of the RegisterStartupScript method in conjunction with the http://msdn.microsoft.com/en-us/library/system.web.ui.page.isstartupscriptregistered.aspx method. If the ECMAScript written in the code declaration block has not already been registered, as determined by the http://msdn.microsoft.com/en-us/library/system.web.ui.page.isstartupscriptregistered.aspx method, then a RegisterStartupScript call is made.

<%@ Page Language="VB"  %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim csname1 As String = "PopupScript"
 
    Dim csname2 As String = "ButtonClickScript"
 
    If Not IsClientScriptBlockRegistered(csname1) Then
      Dim cstext1 As String = "<script type=""text/javascript"">" & _
        "alert('Hello World');</" & "script>"
      RegisterStartupScript(csname1, cstext1)
    End If
 
    If Not IsClientScriptBlockRegistered(csname2) Then
      Dim cstext2 As New StringBuilder()
      cstext2.Append("<script type=""text/javascript""> function DoClick() {")
      cstext2.Append("Form1.Message.value='Text from client script.'} </")
      cstext2.Append("script>")
      RegisterClientScriptBlock(csname2, cstext2.ToString())
    End If
  End Sub
</script>
<html  >
  <head>
  <title>RegisterClientScriptBlock Example</title>
  </head>
  <body>
   <form id="Form1"
     runat="server">
    <input type="text" id="Message" /> <input type="button" value="ClickMe" onclick="DoClick()" />
   </form>
  </body>
</html>
Hope this will help you :-)
  Blair Yumi replied to Vickey F
10-May-11 11:22 PM
So basically, what it does is to disable the function the back button of my browser right?
  Blair Yumi replied to James H
10-May-11 11:26 PM
I dont get it. It doesnt have any effect. Here's what I did with your code: Tell me if its right

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="AddDealerReq.aspx.vb" Inherits="AddDealerReq" %>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
  Dim csname1 As String = "PopupScript"
   
  Dim csname2 As String = "ButtonClickScript"
   
  If Not IsClientScriptBlockRegistered(csname1) Then
    Dim cstext1 As String = "<script type=""text/javascript"">" & _
    "alert('Hello World');</" & "script>"
    RegisterStartupScript(csname1, cstext1)
  End If
   
    If Not IsClientScriptBlockRegistered(csname2) Then
      Dim cstext2 As New StringBuilder()
      cstext2.Append("<script type=""text/javascript""> function DoClick() {")
      cstext2.Append("Form1.Message.value='Text from client script.'} </")
      cstext2.Append("script>")
      RegisterClientScriptBlock(csname2, cstext2.ToString())
    End If
  End Sub
</script>
  
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<meta http-equiv="Expires" CONTENT="0">   
  <meta http-equiv="Cache-Control" CONTENT="no-cache">   
  <meta http-equiv="Pragma" CONTENT="no-cache">   
  
  <title>AddDealerReq</title>
  <link href="FOS.css" rel="stylesheet" type="text/css" />
  <style type="text/css">
    .style1
    {
      width: 75px;
      height: 2px;
    }
    .style2
    {
      width: 196px;
      height: 2px;
    }
    .style3
    {
      height: 2px;
      width: 19px;
    }
    .style4
    {
      width: 19px;
    }
    .style5
    {
      height: 26px;
      width: 19px;
    }
  </style>
</head>
<body>
  
<script type="text/javascript">
//window.history.forward(1); 
function ConfirmView()
  {   
    var Ok = confirm('There is/are existing vehicle(s) in Network Vehiches for sale, View Vehicle(s)?');
    if(Ok)
    location.href = 'NetworkVehiclesforSale.aspx';
    else
      return false;
  }
function ConfirmSave()
  {    
    var Ok = confirm('Proceed to Save?');
    if(Ok==true)
      
      var Ok1 = confirm('There is/are existing vehicle(s) in Network Vehiches for sale, View Vehicle(s)?');
       if(Ok1==true)
        
       location.href = 'NetworkVehiclesforSale.aspx';
       else if(Ok1!=true)
        return false;
        
    else if(Ok!=true)
      return false;
  }
</script>
  <form id="form1" runat="server">
  <div>
    <div>
      <br />
      <asp:Label ID="Label8" runat="server" Font-Bold="True" Text="Create Requirement"
        Width="312px"></asp:Label><br />
      <table>
        <tr>
          <td style="width: 75px" class="labelRight">
            Model:</td>
          <td style="width: 196px">
          <asp:DropDownList ID="cboModel" runat="server" Width="208px" 
            AutoPostBack="True">
          </asp:DropDownList>
          </td>
          <td class="style4">
          </td>
        </tr>
        <tr>
          <td style="width: 75px" class="labelRight">
            Variant:</td>
          <td style="width: 196px">
            <asp:DropDownList ID="cboVariant" runat="server" Width="208px" 
              AutoPostBack="True">
            </asp:DropDownList>
          </td>
          <td class="style4">
          </td>
        </tr>
        <tr>
          
          
          <td style="width: 75px; height: 26px;" class="labelRight">
            Color:</td>
          <td style="width: 196px; height: 26px;">
            <asp:DropDownList ID="cboColor" runat="server" Width="208px" 
              AutoPostBack="True">
            </asp:DropDownList>
          </td>
          <td class="style5">
          </td>
        </tr>
        <tr>
          <td class="style1">
          </td>
          <td class="style2">
  
            <asp:Button ID="cmdSave" runat="server" Text="Save" 
              Width="66px" />  
                
            <asp:Button runat="server" Text="Cancel" Width="69px" />
          </td>
          <td class="style3">
          </td>
        </tr>
      </table>
    </div>
    
  </div>
  <asp:Label ID="lbl" runat="server" Text="Label"></asp:Label>
  </form>
</body>
</html>
  Riley K replied to Blair Yumi
10-May-11 11:32 PM

After sign out when the user press BACK button on the browser, it gets him to the members page.

Logicaly, it's done on the client side and we cannot do much from the code-behind. So, in order to prevent Browser BACK button click after SignOut, we have to use some javascript.

The first and easiest approach to acomplish this is by using the following javascript code:

<body onload="javascript:window.history.forward(1);">

 This code should be placed on the <body> tag of the Members page where Log out button appears.

The problem is that this code will work perfectly on IE (Internet Explorer) but won't work at all for Mozilla Firefox 3.x versions.

So, in order to make this work on Mozilla Firefox, I've prepared Javascript function which is:

<script type="text/javascript" language="javascript">  
function disableBackButton()
{
window.history.forward()

disableBackButton(); 
window.onload=disableBackButton(); 
window.onpageshow=function(evt) { if(evt.persisted) disableBackButton() } 
window.onunload=function() { void(0) } 
</script>

then call noBack() function on <body> on the following way:
<body onload="noBack();">

This code will not let the user get BACK after Sign out.
  James H replied to Blair Yumi
10-May-11 11:41 PM
My suggestion is to write the logout information into cookie, and check the cookie every time page load. Then we can redirect the url to the login page when detect the logout information in page load.

For more information and sample code, please refer to my reply in the following thread:

disable back button of browser so that a user can't go on previous pages after signout

Based on my understanding, your purpose is not to disable the back button. Actually you want to prevent user from back to the previous page after logout. If I have misunderstood you concern, please let me know.
 
For this scenario, my idea is to write a cookie when logout (check the “SetLogoutCookie” function), and read the cookie when page load for each web page except login.aspx (check the “RedirectToLoginPage” function). If the data in cookie means logout then redirect current page to login.aspx. For example, I have provided the following code for your reference. Hope it is helpful to you.
 
************default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>Untitled Page</title>
  <script type="text/javascript">
    function SetLogoutCookie(value)
    {
      var exdate=new Date();
      exdate.setDate(exdate.getDate()+1);
      var expires = "; expires="+exdate.toGMTString();
      document.cookie = "logout=" + value + expires+"; path=/";
    }
 
    function Checklogout()
    {
      var c_start = document.cookie.indexOf("logout=");
      if (c_start!=-1)
      {
        c_start=c_start + 7;
        c_end=document.cookie.indexOf(";",c_start)
        if (c_end==-1)
        {
          c_end=document.cookie.length;
        }
        if(document.cookie.substring(c_start,c_end) == "true")
        {
          return true;
        }        
      }
      return false;
    }
 
    function RedirectToLoginPage()
    {
      if (Checklogout())
      {
        window.location = "login.aspx";
      }
    }
  </script>
</head>
<body onload="RedirectToLoginPage()">
  <form id="form1" runat="server">
  <div>
    <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" OnClientClick="SetLogoutCookie('true')">Log out</asp:LinkButton>
  </div>
  </form>
</body>
</html>
 
*************default.aspx.cs
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
      FormsAuthentication.SignOut();
      FormsAuthentication.RedirectToLoginPage();
    }
 
  
 
************ login.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>Untitled Page</title>
  <script type="text/javascript">
    function SetLogoutCookie(value)
    {
      var exdate=new Date();
      exdate.setDate(exdate.getDate()+1);
      var expires = "; expires="+exdate.toGMTString();
      document.cookie = "logout=" + value + expires+"; path=/";
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    Name:<asp:TextBox ID="TBName" runat="server">test</asp:TextBox>
    <br />
    Password:<asp:TextBox ID="TBPassword" runat="server" TextMode="Password"></asp:TextBox>
    <br />
    <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" OnClientClick="SetLogoutCookie('false')">Login</asp:LinkButton></div>
  </form>
</body>
</html>
 
************ login.aspx.cs
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
       if (FormsAuthentication.Authenticate(TBName.Text, TBPassword.Text))
       {
        FormsAuthentication.RedirectFromLoginPage(TBName.Text,false);
       }
    }
 
 
************ web.config
    <authentication mode="Forms">
    <forms name="appNameAuth" path="/" loginUrl="login.aspx" protection="All" timeout="30">
      <credentials passwordFormat="Clear">
      <user name="test" password="test" />
      </credentials>
    </forms>
    </authentication>
    <authorization>
    <deny users="?" />
    </authorization>
 
 
P.S. You can put the JavaScript code to a separate js file, and include the file in each page.
  TSN ... replied to Blair Yumi
10-May-11 11:45 PM
to disable back button from javasscript you can use below code..

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
</head>
<body onload="disableBackButton()">
<form id="form1" runat="server">
<div>
This is First page <br />
<br />
Go to Second page
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/Default2.aspx">Go to Second Page
</asp:LinkButton></div>
</form>
</body>
</html>


if you want to disable from codebehind...

If you want to disable back button using code behind of aspx page,than you need to write below mentioned code
 
C# code behind
 
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
 
//We can also achieve this by disabling browser caching or cache by writing this //line of code either in Page_load event or in Page_Init event
 
protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}


use any of the above ..

hope it helps you...

  Blair Yumi replied to James H
10-May-11 11:55 PM
My cocnern is that, when I press the back button, the function in javascript executes again. like the MessagBox comes up again. that's what happens. I want is, when the user press the back button, the function will not execute again. That's all. Thanks
  Anoop S replied to Blair Yumi
11-May-11 12:45 AM
The best way is use replace Method, When a document is replaced, it is also removed from the history object. Moreover, the user interface navigation methods, such as the Back and Forward buttons, will no longer access the URL.
object.replace(sURL)
http://msdn.microsoft.com/en-us/library/ms536712.aspx
  Blair Yumi replied to Anoop S
11-May-11 01:29 AM
where will i put the object.replace(surl) code? and what url will i put there? the destination or the source?thanks
  Anoop S replied to Blair Yumi
11-May-11 01:39 AM
In the backbutton, sUrl means the page url you want to show on backbutton click. When a document is replaced, it is also removed from the history object. Moreover, the user interface navigation methods, such as the Back and Forward buttons, will no longer access the URL.
  Blair Yumi replied to Anoop S
11-May-11 03:12 AM
Hi, can any one help me on Exporting Gridview to Excel. This works just fine, but with full page datagridview only, when It has another page (hyperlink to the nextpage), it prints just like the image of datagridview, with pageindex below and not exporting the other contents of the pages. It should generate a whole excel page whwre in all the data of my gridview is eported. Please Help me. Thank You. Here's my code:

Protected Sub btnExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcel.Click
    ' Clear the response   
    Response.Clear()
  
    ' Set the type and filename   
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
    Response.Charset = ""
    Response.ContentType = "application/vnd.xls"
  
    ' Add the HTML from the GridView to a StringWriter so we can write it out later   
    Dim sw As System.IO.StringWriter = New System.IO.StringWriter
    Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
    grdNetWrkReq.RenderControl(hw)
  
    ' Write out the data   
    Response.Write(sw.ToString)
    Response.End()
  End Sub
  
  Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
  
  End Sub
  Blair Yumi replied to Anoop S
11-May-11 03:33 AM
but it gives me an error. The Object has no Replace Property.
  Anoop S replied to Blair Yumi
11-May-11 03:46 AM
what version of .net you are using? its available for 3.0 or higher
  Blair Yumi replied to Anoop S
17-May-11 09:25 PM
it's 3.5
Create New Account
help
new HtmlTextWriter(stringWrite); GridView1.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { / / Confirms that an HtmlForm control is rendered for the specified ASP.NET server cs = Page.ClientScript; / / Check to see if the client script is already registered. if (!cs.IsClientScriptBlockRegistered(csType, csName)) { cs.RegisterClientScriptBlock(csType, csName, csText.ToString()); } } public override void VerifyRenderingInServerForm(Control control) { / * Verifies that the control is rendered * / } protected void OnPaging( object sender, GridViewPageEventArgs e
cs = Page.ClientScript; / / Check to see if the client script is already registered. if (!cs.IsClientScriptBlockRegistered(csType, csName)) { cs.RegisterClientScriptBlock(csType, csName, csText.ToString()); } } public override void VerifyRenderingInServerForm(Control control) { / * Verifies that the control is rendered * / } protected void OnPaging( object sender, GridViewPageEventArgs e
cs = Page.ClientScript; / / Check to see if the client script is already registered. if (!cs.IsClientScriptBlockRegistered(csType, csName)) { cs.RegisterClientScriptBlock(csType, csName, csText.ToString()); } } public override void VerifyRenderingInServerForm(Control control) { / * Verifies that the control is rendered * / } protected void OnPaging( object sender, GridViewPageEventArgs e
protected override void OnPreRender(EventArgs e) { if (Page ! = null) { StringBuilder sb = new StringBuilder(); if (!Page.IsClientScriptBlockRegistered("WidthAdjuster")) { sb.Append("<script language = \ "JavaScript \ " type = \ "text / javascript \ "> \ n"); sb.Append("<!- - / / WidthAdjuster by Wesley if(e.clientX)mX = e.clientX+dB.scrollLeft;}}"); sb.Append(" / / - -> \ n"); sb.Append("< / script> "); Page.RegisterClientScriptBlock("WidthAdjuster", sb.ToString()); sb = new StringBuilder(); } sb.Append("<script language = \ "JavaScript \ " type = \ "text / javascript \ "> \ n sb.ToString()); } base.OnPreRender(e); } protected override void Render(HtmlTextWriter writer) { if (Page ! = null) { Page.VerifyRenderingInServerForm(this); } base.Render(writer); } } } check here http: / / forums.asp.net / p / 960850 / 1191965.aspx http