Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript in code-behind problem 1

Status
Not open for further replies.

LauraCairns

Programmer
Joined
Jul 26, 2004
Messages
173
Location
GB
I have code which checks whether a datagrid is empty and if it is it shows a panel on my page. If its not empty then Im using the server.transfer to go to another page so as im able to use the items in an array list. My problem is that I also have had to incorporate some Javascript to see whether the user is ok with moving forward. Everything is fine and works apart from when the user clicks cancel on the pop-up Internet Explorer window it stills lets them move on. I need to be able to introduce something which keeps the user on the same page if they click cancel.

Has anyone any idea how I can achieve this or if this is possible in my circumstances.

private void checkdgSearchResults()
{
if(this.DataGrid1.Items.Count == 0)
{
this.pnlSearchAddresses.Visible = true;
}

else
{

ArrayList addresses;
addresses = (ArrayList) ViewState["Addresses"];
Context.Items["TransferAddresses"] = addresses;
string surname = this.Textbox7.Text;
Context.Items["test"] = surname;
Response.Write("<script language='JavaScript'>(window.confirm('The search fee will now be deducted for the criteria entered. Do you wish to continue?'));</script>");
Server.Transfer("ArrayListItemsDisplayed.aspx");

}
}
 
The JavaScript window.cofirm() method returns a boolean. If the boolean is false, navigation is cancelled.

Here is an example of a working "confirm". Notice the importance of the "return" keyword.

Code:
<HTML>
<head>
<script>
function confirmNav()
{
  var response = window.confirm("Do you really want to go to Yahoo?");
  return response;
}
</script>
</head>

<body>
This is my page.
<a href="[URL unfurl="true"]http://www.yahoo.com"[/URL] onclick="return confirmNav();">Go to Yahoo?</a>
</body>
</HTML>



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Thats great but have you any idea how I can use this in the code behind.
My problem is that Im using a server.transfer to redirect the page and take accross an arraylist as my post outlines. Although I also need the Javascript to bring up the messagebox and ask the user if they want to continue. If they say yes then I need to let the server.transfer kick in otherwise I need the user to remain on the same page. Is there any way I can do this???
 
The way you typically combine server-side and client-side events on a single control is to have a hidden form element. The control will run a JavaScript. If conditions are properly met, the JavaScript sets the value of the hidden control, and then submits the form:

document.Form1.submit()

If conditions are NOT met, the JavaScript returns "false", and the page is not submitted to the server.

You can also set a session state variable instead of a hidden form element, if you choose.

Then, in your Page_Load event handler, check the value of the hidden or session state variable and perform your server.transfer or response.redirect accordingly.

The key is that the initial control is not a web control. It's a standard hyperlink or button with the onclick set to a JavaScript.

The JavaScript itself modifies form values and submits to the server (or not).







Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
I sort of get the idea, but irs writing the actual code for my particular scenario is the problem. I don't want to use a session variable hence the reason for using the server.transfer being used. I think im close but I can't seem to get it. If I could modify this code:

Response.Write("<script language='JavaScript'>if (window.confirm('The search fee will now be deducted for the criteria entered. Do you wish to continue?')) document.location.href='WebForm2.aspx'; else document.location.href='DebtorEnquiry.aspx';</script>");

to something like this

Response.Write("<script language='JavaScript'>if (window.confirm('The search fee will now be deducted for the criteria entered. Do you wish to continue?')) Server.Transfer("../Internet/WebForm2.aspx"); else document.location.href='DebtorEnquiry.aspx';</script>");

If i could do this id be flying. I need the server.transfer instead of the href =.

Are you able to help me?? Im really stuck on this one
 
Your problem is conceptual. You seem to have a problem understanding WHEN code runs.

Server-side code ONLY runs when the form is submitted to the server. In other words, a client-side JavaScript CANNOT "call" or "initiate" a server-side method, such as Server.Transfer. It can only change the values of form elements PRIOR TO submitting the form. Then server side code takes over.

So your example "ideal code" would never work. You have two workflow options:

1) Run a client-side script that, conditionally, submits the form. Then and only then can server-side code run.

2) ALWAYS submit the form, and let the server-side code write a new script block which runs when the page is re-rendered in the browser. By that time, it's too late.

Why do you think you need to do a Server.Transfer? Server.Transfer does a server-side focus change from one web form to another, potentially (if an overload of the transfer method with a second argument, boolean, is set to true) transfer the values of the initial webform,s form elements along to the new webform. (A nice idea is for the new webform to have the same id's as the old, so that the values are automatically transferred/set in the new form.)

That's kind of a neat trick, but rarely necessary.

What's wrong with doing this:

1. Submit the form.

2. Check to see if datagrid is NOT empty in server-side code

3. If it is NOT empty, response.write a script, just like you're doing.

4. That script pops up a confirm().

5. If the confirm returns false, set a hidden variable equal to "false", if true, "true".

6. Submit the form.

7. Server side, check value of hidden field.

8. If "true", do your Server.Transfer("WebForm2.aspx",true). If False, return whatever page you want via Response.Redirect(), a "TransactionCancelled.aspx" for example.

What you have to undersand is that your script can only really submit the form. Your conditional server.transfer can only happen in server-side code.



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
I get the idea now but not sure how exactly to write the code which does point 8 above.

The javascript confirm() - how exactly do I write this so as it returns a variable true or false??

Then how do I write my code to do point 8. If false I simply want the page to stay on the current page it is trying to submit from.

I just can't seem to write the code for my example. I'm very knew to coding which is why im probably having so much trouble with this. Can you help me please please!!
 
Ok. Here is a COMPLETE SAMPLE for you!

First, the WebForm/HTML:

Code:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="testTransfer.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="[URL unfurl="true"]http://schemas.microsoft.com/intellisense/ie5">[/URL]
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 24px" runat="server">Do you want to do a Server.Transfer()?</asp:Label>
<asp:CheckBox id="CheckBox1" style="Z-INDEX: 102; LEFT: 56px; POSITION: absolute; TOP: 64px" runat="server" Text="Yes, I do!"></asp:CheckBox>
<asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 184px; POSITION: absolute; TOP: 64px" runat="server" Text="Next..."></asp:Button>
<asp:TextBox id="TextBox1" style="VISIBILITY: hidden; Z-INDEX: 104; LEFT: 64px; POSITION: absolute; TOP: 104px" runat="server"></asp:TextBox>
</form>
</body>
</HTML>

Notice, that in the TextBox1, the style sets the visibility to hidden. If you change the TextBox1.Visible property to "false", the control won't render. So make it invisible via the CSS property, as in my example.

Now, here is the code-behind page:

Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace testTransfer
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public class WebForm1 : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Label Label1;
		protected System.Web.UI.WebControls.CheckBox CheckBox1;
		protected System.Web.UI.WebControls.TextBox TextBox1;
		protected System.Web.UI.WebControls.Button Button1;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if (TextBox1.Text == "true")
			{
				Server.Transfer("transferHere.aspx",true);
			}

			if (TextBox1.Text == "false")
			{
				Response.Write("Please make up your mind.");
				Response.End();
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Button1.Click += new System.EventHandler(this.Button1_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void Button1_Click(object sender, System.EventArgs e)
		{
			if (CheckBox1.Checked)
			{
				//User checked "Yes, I want to do a Server.Transfer()
				//Make them confirm it.
				this.Page.RegisterStartupScript("confirmID","<script> " +
					"var response = window.confirm(\"Really?\"); "+
					"if (response == true) " +
					"{ " +
					"document.Form1.TextBox1.value = \"true\"; " +
					"} " +
					"else " +
					"{ " +
					"document.Form1.TextBox1.value = \"false\"; " +
					"} document.all.Form1.submit();</script> ");
			}
			else
			{
				Response.Write("I didn't transfer you.");
				Response.End();
			}
		}
	}
}

So here's what's going on:

1. Submit the Form via the button.

2. Server-side: If the checkbox is checked (this is where you'd check your datagrid), then register a script.

3. Client-side: Now the browser has control, and runs the script. If the user clicks "ok", set TextBox1 = "true". Submit the form.

4. Server-side: check the value of TextBox1. If it's true, do your Server.Transfer().



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Better version of the code-behind. In this one, if the user doesn't confirm, then nothing at all happens. It doesn't go back to the server:

Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace testTransfer
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public class WebForm1 : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Label Label1;
		protected System.Web.UI.WebControls.CheckBox CheckBox1;
		protected System.Web.UI.WebControls.TextBox TextBox1;
		protected System.Web.UI.WebControls.Button Button1;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if (TextBox1.Text == "true")
			{
				Server.Transfer("transferHere.aspx",true);
			}
			TextBox1.Text = "";

		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Button1.Click += new System.EventHandler(this.Button1_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void Button1_Click(object sender, System.EventArgs e)
		{
			if (CheckBox1.Checked)
			{
				//User checked "Yes, I want to do a Server.Transfer()
				//Make them confirm it.
				this.Page.RegisterStartupScript("confirmID","<script> " +
					"var response = window.confirm(\"Really?\"); "+
					"if (response == true) " +
					"{ " +
					"document.Form1.TextBox1.value = \"true\"; " +
					"document.all.Form1.submit(); } " +
					"</script> ");
			}
			else
			{
				Response.Write("I didn't transfer you.");
				Response.End();
			}
		}
	}
}

Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
This is amazing managed to play about this code all morning and got it integrated perfectly into my scenario.

Your a legend I owe you big time. If your ever over in Belfast I'll buy you a couple of pints.

The only small thing i wasn't able to do was the stylesheet part to make the textbox invisible. I simply allow the textbox to be shown at present. How exactly do you add this to a style sheet, we have an existing style sheet for the page but I don't want to mess about with it to much. Can I do a style like invisible for a particular textbox??

Thanks again for your help, your a star/legend/amazing!!
 
One last problem I noticed with this is that when the user click back in the browser window then the javascript pops-up again. Is there any way to stop this
 
Laura,

I do travel a bit, doing PostScript consulting/training. Who knows?

To your questions:

You can do style's inline, if you choose. Just add:

Code:
style="VISIBILITY: hidden"

to the tag. Here it is again from my HTML/WebForm posting:

Code:
<asp:TextBox id="TextBox1" style="VISIBILITY: hidden; Z-INDEX: 104; LEFT: 64px; POSITION: absolute; TOP: 104px" runat="server"></asp:TextBox>

You don't have to add it to the stylesheet. You can add it directly to this one specific textbox, leaving your stylesheet intact.

Your second question involved the user clicking "back", and so re-firing the script.

The solution is to have that script "turn itself off" the first time it runs. You can do this by having the script change the body tag's onload attribute to an empty string. Here is a revised version of that section of code:

Code:
				this.Page.RegisterStartupScript("confirmID","<script> " +
					"var response = window.confirm(\"Really?\"); "+
					"if (response == true) " +
					"{ document.body.onload = \"\";" +
					"document.Form1.TextBox1.value = \"true\"; " +
					"document.all.Form1.submit(); } " +
					"</script> ");

Notice the added: document.body.onload="". So if the user runs this script, the script is "detached" from the body onload event. So if they click back, no script runs.




Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Thats great!! thank you very much!! Your a star!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top