ASP.NET Client-Side Script FAQ
(Various contributors)

We have a fair amount of forum questions here on Eggheadcafe.com that center around the area of client-side scripting with ASP.NET, and we thought it would be about time to start an FAQ article on the subject. We'll include all the basics of client - side script with ASP.NET here, drawn from reliable sources (and simplified!) along with our own "discoveries". We'll also insert links to other resources where appropriate. This is a community "work in progress" which we will add to on a regular basis, so please feel free to take advantage of the little "article discussion forum" at the bottom to post or answer questions and make requests, as well as to make repeat visits to see "what's new" on the page! All contributions are encouraged, either via the discussion at the bottom of this page, or via email.



Basic Concepts:

There are two important component parts of any ASP.NET "page" - the ".ASPX" portion, which is really a modified HTML page that holds the asp:control server tags, client script, and HTML elements, and the "Codebehind" or server-side portion of the page, which can be either inside <script runat="server" ... tags, or more typically, compiled into the .NET assembly that represents all the pages of the particular ASP.NET Web application. Client-side script (normally JavaScript or "JScript" if you prefer to use the Microsoft "branded" name) always appears in the rendered HTML that shows up in your browser when you request an ASP.NET page, because in the final analysis, it doesn't matter what technology is used to "generate" a page- its still just HTML, CSS and Script when its done and the browser has consumed it.

The script that shows up in the browser - rendered version of the page, however, could be generated by either having it prewritten, sitting inside <script></script> tags in the ASPX portion (or with a src=<scriptlocation> attribute), or it could be generated from server side processing, as we will soon see.

ASP.NET Intrinsic Client-Script Related Methods

ASP.NET has several built in methods of the Page class that were specifically designed to help with client-side scripting. Let's look at these first:

RegisterClientScriptBlock and RegisterStartupScript methods of the Page class.
These methods identify your script with a string key, so that multiple server control instances can request the script block without it being inserted in the output more than once. The IsClientScriptBlockRegistered and IsStartupScriptRegistered methods of the Page object are used to determine if the script has already been registered.

Differences between RegisterClientScriptBlock and RegisterStartupScript

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object's <form runat=”server”> element. The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object's <form runat=”server”> element. You need to include the <script> start and end tags in the output when using the above methods. The choice of which method to use really depends on the "order" in which you want your script to be run by the browser when rendering the page.

Both of these methods take two strings as input. The second parameter, script , is the client-side script-including the opening and closing <script> tags. The first parameter, key , serves as a unique identifier for the inserted client-side script.

There are two different methods for emitting client-side script because client-side script generally can have one of two purposes: code that is designed to run immediately when the page is loaded, and code that is designed to run when some client-side event occurs. An example of code designed to run when the page is loaded is script that sets the focus to a textbox. When you visit Google, a piece of client-side code is executed when the page is loaded to set the focus to the search textbox.

RegisterOnSubmitStatement method

This method allows a page to access the client OnSubmit event. The script should be a function call to client code registered elsewhere.Parameters:
key Unique key that identifies a script block.
script The client-side script to be sent to the client.

Example (This also uses the RegisterHiddenField method):

void Page_Load(Object sender, EventArgs e)
{
String scriptString = "<script language=JavaScript>function doClick() {"; scriptString += "document.write('<h4>' + myForm.myHiddenField.value+ '</h4>');}<";
scriptString += "/" + "script>";
RegisterHiddenField("myHiddenField", "Welcome to Microsoft .NET!");
RegisterOnSubmitStatement("submit", "document.write('<h4>Submit button clicked.</h4>')"); RegisterStartupScript("startup", scriptString);
}

Preventing Form Submissions with Client Script

The confirm dialog box is displayed using the script confirm(message) function. It displays a dialog box with the text specified by the message input parameter along with OK and Cancel buttons. The confirm(message) function returns true if the user clicks OK and false if they click Cancel.

Confirm dialog boxes are normally used to ensure that the user wants to continue before submitting a form. When an HTML element is clicked to submit a form, if it fires a client-side event handler that returns false, the form submission is canceled. Typical usage in a Web page as follows:

<form ...>
<input type="submit" value="Click To Submit" onclick="return confirm('Are you sure you want to submit this form?');" /> </form>

When the user clicks the "Click To Submit" button, they see the confirm dialog. If the user clicks OK, confirm() will return true and the form will be submitted. If, however, they click Cancel, confirm() will return false and the form's submission will be canceled.

Code such as the above can be easily attached to the Button that submits a form as follows:

private void Page_Load(object sender, System.EventArgs e)
{
string scr ="return confirm('Are you sure you want to submit this form?');";
this.Button1.Attributes.Add("onclick",scr);
}

Preventing Form Submissions that programmatically call __doPostBack

Listening for form.onsubmit (by using Page.RegisterOnSubmitStatement ) is not sufficient because it won't fire when the form is submitted programmatically as with ASP.NET's __doPostBack method. Here is a solution that "hijacks" the __doPostBack method to ensure that your onSubmit handler is executed first:

In the ASPX portion of your page:

<HTML>
<HEAD>
<script>
// save a reference to the original __doPostBack
var __oldDoPostBack = __doPostBack;
// replace __doPostBack with another function
__doPostBack = AlwaysFireBeforeFormSubmit;
function AlwaysFireBeforeFormSubmit (eventTarget, eventArgument) {
// do whatever pre-form submission
// chores you need here (example:)

return confirm('Are you sure?');
// finally, let the original __doPostBack do its work
return __oldDoPostBack (eventTarget, eventArgument);
}
</script>

Then in your Page_Load:

private void Page_Load(object sender, System.EventArgs e)
{
System.Web.UI.HtmlControls.HtmlForm frm =(System.Web.UI.HtmlControls.HtmlForm)this.FindControl("Form1");
frm.Attributes.Add("onSubmit","AlwaysFireBeforeFormSubmit();");
}

ValidateRequest Directive

ASP.Net 1.1 will not allow html code to be sent to the server unless you use the page directive validateRequest = "false". This can also be set globally in web.config in the pages element:

  Add the "pages" line within the pre-existing <system.web> tag:
  <system.web>
    <pages validateRequest="false" />
  </system.web>


NOTE: If you use the above, your site may be vulnerable to cross-site scripting attacks, unless your code was already well-written to prevent that.

GetPostBackClientEvent Method

The GetPostbackClientEvent method returns a string containing the client-side script for the postback event of a given control:

Parameters:
control - the control that should be passed to the postback method on the client side as the source of the postback event.
argument- the argument that will be passed to the postback method

String = GetPostBackClientEvent(control, argument)

GetPostBackClientHyperlink Method

The GetPostBackClientHyperlink method returns a string representing a hyperlink to the client-side script call that initiates the postback process.

Parameters:
control - the control that should be passed to the postback method on the client side as the source of the postback event.
argument- the argument that will be passed to the postback method

This method allows developers to create hyperlinks that will cause the page to postback to the server. For example:

<a id="link1" href="<%=GetPostBackClientHyperlink(button1, "submit") %>">Link 1</a>

The above creates a link to the postback method associated with the control with id "button1", and passes in an argument of "submit".

The GetPostBackEventReference Method

Gets a reference to the client-side function that initiates the postback. When building web pages, it can be helpful to get a reference to the postback script function in order to programmatically cause the page to postback. This method will cause the page to postback, indicating that the specified control caused the postback.

String = GetPostBackEventReference(control, [argument])

Parameters:
control - the control that should be passed to the postback method on the client side as the source of the postback event.
argument- the argument that will be passed to the postback method

The RegisterArrayDeclaration Method

This method creates a client-side script block that declares an array. In addition, you can add an element to the array. Subsequent calls to this method using the same array name add new elements to the same array. In this way, multiple controls in a page request can add themselves or elements of their content to this array.

Void RegisterArrayDeclaration (arrayname, value)

Parameters:

arrayname (string)- the name to give to the client script array variable
value (string) - the value to be added to the array. Can be the name of an object or control on the page.

Example:

RegisterArrayDeclaration("TextBoxes","TextBox1")
RegisterArrayDeclaration("TextBoxes", "TextBox2")

Client - side output of the above two calls would look like this:

<script language="javascript" >
<!--
var TextBoxes = new Array(TextBox1, TextBox2);
// -->
</script>

Causing a page to reload via server - side action:

// cause page to reload from server-side Response object:
Response.Write("<script>window.location.reload(true);</script>");

// Cause page to repeatedly reload
Response.Write("<script>window.setTimeout("window.location.reload(true)", 1000);</script>");