Although usually used,. net + client scripts insert client scripts from ASP. NET Server controls

Source: Internet
Author: User
Tags html comment

Insert client scripts from ASP. NET Server controls
Scott Mitchell

August 2003

Applicable:
Microsoft? ASP. NET

Prerequisites: This document assumes that you are familiar with ASP. NET.

Difficulty: 2

Abstract: although all the functions of ASP. NET Server controls can be executed on the server, adding client scripts can greatly enhance the availability of server controls. This article will explore two ways for server controls to send client scripts, and build two server controls using these technologies:
PopupGreeting
A server control that displays the client mode dialog box with a specific message on the Web page loaded for the first time;
ConfirmButton
, An enhanced Button Web control. If you click this Button, a JavaScript
Confirm ()
Dialog box. (This article contains links to English sites .)

Download InjectingClientSideScript. msi.

Directory
Introduction
Use RegisterStartupScript () and RegisterClientScriptBlock () to add client script Blocks
Discuss IsStartupScriptRegistered () and IsClientScriptBlockRegistered ()
Send client script blocks from ASP. NET Server controls
Send HTML attributes of the Web Control of ASP. NET Server
Summary

Introduction
Technically speaking, Microsoft? All functions of ASP. NET Server controls can be executed on the server. However, adding client scripts can greatly enhance the availability of server controls. For example, ASP. NET verifies that the Web control can perform all verification checks on the server side. However, for a browser of a higher version, the Web control is verified by sending a client script. That is to say, users of these browsers can get a dynamic experience with better response results.

When developing ASP. NET Server controls, you may wish to ask yourself how to enhance availability by using client scripts. Once a feasible solution is found, the other thing to do is to enhance the server control function so that it can send appropriate client scripts.

The ASP. NET Server Control can send two client scripts:

Client script block
Client HTML attributes
Client script blocks are usually written in JavaScript, which usually contain functions executed when a specific client event occurs. The client HTML attribute allows you to associate client events with client scripts. For example, the following HTML page contains the client script block, which contains
DoClick ()
. The page also contains a button
<Input>
HTML element creation ).
Onclick
Attribute and
DoClick ()
Function binding. That is to say, you only need to click this button to start execution.
DoClick ()
Client code in the function. In this example, a pop-up dialog box is displayed (figure 1 ).

<Html>
<Body>
<Form>
<Script language = "JavaScript">
<! --
Function doClick (){
Alert ("You clicked me! ");
}
// -->
</Script>

<Input type = "button" onclick = "doClick ()" value = "Click Me! "/>
</Form>
</Body>
</Html>

Figure 1 shows how to Click "Click Me !" Button.

 

Figure 1: Click "Click Me !" Pop-up dialog box displayed when button

The client scripts on the preceding HTML page are worth noting. First, the client script block is included in the HTML annotation (
<! --
And
-->
. This is because if the script block is not added to the HTML comment, the old browsers that cannot recognize the script will display
<Script>
Block content. In addition, note that there is a JavaScript comment before the end mark of the HTML comment in the script block, that is
//
. This is because the earlier version of Netscape encountered
-->
Will throw a JavaScript analysis exception, so you must comment it out. Fortunately, modern browsers do not need this extra action, so you do not have to take this precaution when developing Web pages for intranets or other browser-controlled environments.

If you are not familiar with client scripts, the alert (string) function is used to display a mode pop-up dialog box. The messages contained in the dialog box are specified by the string parameter. All HTML elements have several client attributes that can be bound to a client JavaScript code (for example,
Onclick
,
Onmouseover
,
Onmouseout
,
Onfocus
And
Onblur
And so on ). For example, in the preceding HTML page,
<Input>
Element
Onclick
Property bound
DoClick ()
Function, so when you click this button
DoClick ()
Function. For a list of JavaScript events and their associated HTML attributes, see Introduction to Dynamic HTML. For more information about client JavaScript, see HTML and Dynamic HTML.

In this article, we will learn how to send client script blocks and HTML element attributes in ASP. NET Server controls. First, we will discuss how to use
System. Web. UI. Page
To add the client script block to the ASP. NET Web page. The two methods are as follows:
RegisterStartupScript ()
And
RegisterClientScriptBlock ()
. After learning this knowledge, we will build a simple server control that will display a client pop-up dialog box each time a page is loaded. Later, we will learn how to add HTML attributes to the HTML elements of the ASP. NET Server Control. Finally, we will summarize all the knowledge and build a ConfirmButton Web control. When you click this control, a dialog box will be displayed to you asking if you want to continue.

Use RegisterStartupScript () and RegisterClientScriptBlock () to add client script Blocks
The System. Web. UI. Page class contains two methods to send client script code to the HTML provided by ASP. NET Web Page:

RegisterStartupScript (key, script)
RegisterClientScriptBlock (key, script)
Both methods accept two strings as input. The second parameter script is the client script to be inserted into the page, including
<Script>
. The first parameter key is the unique identifier of the inserted client script.

The only difference between the two methods is that the script block is sent from "where.
RegisterClientScriptBlock ()
At the beginning of the Web form (followed
<Form runat = "server">
) Send the script block, and
RegisterStartupScript ()
At the end of the Web form
</Form>
Before the identifier) Send the script block.

Why are there two different methods to send client scripts? To better understand this, we must first understand that client scripts can be divided into two types: one is the code that runs immediately after the page is loaded, one is the code that runs only when some client events occur. A common example of the former is to set the focus to the client code of the text box. For example, when you access Google, a small piece of client code is executed after the page is loaded to automatically set the focus to the search text box.

The following is an example of the next type of code (code running in response to client events. In this example, a pop-up dialog box is displayed when you click the button:

<Html>
<Body>
<Form>
<Script language = "JavaScript">
<! --
Function displayPopup (){
Alert ("Hello, world .");
}
// -->
</Script>

<Input type = "button" value = "Click Me! "Onclick =" displayPopup () "/>
</Form>
</Body>
</Html>

In this Code,
<Input>
Marked
Onclick = "displayPopup ()"
Specifies the JavaScript function when a button is clicked.
DisplayPopup ()
It should be run.

RegisterStartupScript ()
The method can be used to add the script block to run after the page is loaded. The script block added in this way is located at the end of the Web form, because the HTML element to be modified must be defined before the script is run. That is, if you want to use a client script to set the focus to the text box, make sure that the HTML mark of the text box is before the script that sets the focus of the text box. For example, the following HTML will display a text box and set the focus to this text box:

<Input type = "text" id = "myTextBox"/>

<Script language = "JavaScript">
<! --
Document. getElementById ("myTextBox"). focus ();
// -->
</Script>

Conversely, the following HTML does not set the focus to the text box, because the text box is defined after the script block:

<Script language = "JavaScript">
<! --
Document. getElementById ("myTextBox"). focus ();
// -->
</Script>

<Input type = "text" id = "myTextBox"/>

Therefore,
RegisterStartupScript ()
Method
<Script>
The block is placed at the end of the Web form to ensure that all HTML elements in the Web form have been declared before the client script is executed.

RegisterClientScriptBlock ()
The script code used to respond to client events. The script block sent using this method is located at the beginning of the Web page, because this method does not require that the script block be placed after all HTML elements.

Discuss IsStartupScriptRegistered () and IsClientScriptBlockRegistered ()
Division
RegisterStartupScript ()
And
RegisterClientScriptBlock ()
In addition to methods,
Page
The class also contains two auxiliary methods that are often used to send client scripts:

IsStartupScriptRegistered (key)
IsClientScriptBlockRegistered (key)
As described above
RegisterStartupScript ()
Or
RegisterClientScriptBlock ()
When you insert a client script block, a keyword is provided to uniquely identify the script block. Both methods accept an input (string key) and return a Boolean value to indicate whether the script block with the specified keyword has been added to the page. Specifically, if the script block with a specific key has been registered, these methods will return True; otherwise, False.

To learn how to use these two methods, you can take a look at ASP. NET to verify Web controls, such as RequiredFieldValidator and RegularExpressionValidator. These controls all use a common validation JavaScript file (
WebValidation. js
), The file is located in
Aspnet_client/system_web/version number
Directory. Therefore, all these controls will send the same script block, which will be called in
WebValidation. js
File to start the client verification process. To complete this process, these controls use
Page
Class
RegisterClientScriptBlock ()
Method, and use keywords
ValidatorIncludeScript
.

What will happen if an ASP. NET Web page contains multiple Authentication Web controls? All these Web controls use the same keywords to send the same script block. If this keyword is used twice
RegisterClientScriptBlock ()
Or
RegisterStartupScript ()
Method, the second call is considered to be a copy of the script block and ignored. Therefore, even if a Web page has multiple verification controls, it only sends an instance of a public script block. However, please note that all the other verification Web controls except the first control will build the public client script to be sent, which is just a waste of time.

In this case, you should use
IsClientScriptBlock ()
And
IsStartupScript ()
Method. In this way, the Web control does not take the time to build the client code to be sent, but checks whether a keyword exists.
ValidatorIncludeScript
The registered script. If it exists, the control will discard building the client script block because the script block has been built by other verification controls on the page.

Therefore, you must call
IsClientScriptBlock ()
Or
IsStartupScript ()
Method to Determine whether to generate a client script. In the following section, we will see some examples. In these examples,
IsClientScriptBlock ()
,
IsStartupScript ()
Methods and
RegisterClientScriptBlock ()
And
RegisterStartupScript ()
Method.

Send client script blocks from ASP. NET Server controls
Remember,
RegisterStartupScript ()
And
RegisterClientScriptBlock ()
The method is
System. Web. UI. Page
Class method. Fortunately, the two methods can be easily called from the ASP. NET Server Control, because
System. Web. UI. Control
Class (all ASP. NET Server controls are exported directly or indirectly from this class) has
Page
Instance reference
Page
Attribute, and this
Page
The instance contains server controls. Therefore, to add a client script block from an ASP. NET Server Control, you only need to use the following syntax:

This. Page. RegisterClientScriptBlock (key, script );
Generally, the task of adding a client script block will use
OnPreRender ()
This method is executed in the pre-rendering stage of the control lifecycle.

Let's create an ASP. NET Server Control that only displays the client pop-up dialog box. This example shows that it is easy to build a control for sending client scripts.

First, in Microsoft? Visual Studio? . NET to create a new Web Control Library project. This will create a new project with only one class.
System. Web. UI. WebControls. WebControl
Export. However, we want this class
System. Web. UI. Control
Class export. Why? Because
WebControl
Class is used to support server controls that display HTML elements, while
Control
Class is used for server controls that do not display as HTML elements.

Most built-in ASP. NET Server controls send an HTML element. For example, the TextBox Web control sends
<Input>
Element, whose type attribute is set to text; the DataGrid Web control sends
<Table>
Element, sent for each record to be displayed
<Tr>
Element, send for each field
<Td>
Column. However, not all controls need to send HTML elements. For example, the Literal control only outputs its Text attribute as is, instead of placing this attribute in an HTML element. Similarly, Repeater does not place its output in HTML elements. Server controls that are displayed as HTML elements, such as TextBox, Button, and DataGrid, are
System. Web. UI. WebControls. WebControl
Controls that do not generate HTML elements, such as Literal and Repeater, are exported from
System. Web. UI. Control
Class.

Since the server control we want to create is invisible (it only sends a client script block that displays the pop-up control), it is best
System. Web. UI. Control
Export, not from
System. Web. UI. WebControls. WebControl
Export.

This control only requires two attributes:

PopupMessage
-Indicates the message string to be displayed in the pop-up dialog box.
Enabled
-Indicates whether to enable the Boolean value of the control. If the control is enabled, the pop-up dialog box is displayed. Otherwise, the dialog box is not displayed. (You must add
Enabled
Attribute, because
Control
Class does not include
Enabled
Attribute, which is implicitly composed
WebControl
Use the exported control .)
In addition to these two attributes, We need to overwrite
OnPreRender ()
Method. Here, we need to call
RegisterStartupScript ()
And pass the unique keyword of the control and the appropriate client script to display the pop-up dialog box. The complete code for this class is as follows:

Using System;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. ComponentModel;

Namespace ClientSideScript
{
/// <Summary>
/// Abstract description of WebCustomControl1.
/// </Summary>
[DefaultProperty ("Text "),
ToolboxData ("<{0}: PopupGreeting runat = server> </{0}: PopupGreeting>")]
Public class PopupGreeting: System. Web. UI. Control
{
[Bindable (true ),
Category ("Appearance "),
DefaultValue ("")]
Public string PopupMessage
{
Get
{
// Check whether this project exists in ViewState
Object popupMessage = this. ViewState ["PopupMessage"];
If (popupMessage! = Null)
Return this. ViewState ["PopupMessage"]. ToString ();
Else
Return "Welcome to my Web site! ";
}

Set
{
// Specify the ViewState variable
ViewState ["PopupMessage"] = value;
}
}

[Bindable (true ),
Category ("Appearance "),
DefaultValue ("")]
Public bool Enabled
{
Get
{
// Check whether this project exists in ViewState
Object enabled = this. ViewState ["Enabled"];
If (enabled! = Null)
Return (bool) this. ViewState ["Enabled"];
Else
Return true;
}

Set
{
// Specify the ViewState variable
ViewState ["Enabled"] = value;
}
}

Protected override void OnPreRender (EventArgs e)
{
Base. OnPreRender (e );

String scriptKey = "inclupopupmessage:" + this. UniqueID;

If (! Page. IsStartupScriptRegistered (scriptKey) & this. Enabled &&
! Page. IsPostBack)
{
String scriptBlock =
@ "<Script language =" "JavaScript" ">
<! --
Alert ("" % POPUP_MESSAGE % "");
// -->
</Script> ";
ScriptBlock = scriptBlock. Replace ("% POPUP_MESSAGE %", this. PopupMessage );

Page. RegisterStartupScript (scriptKey, scriptBlock );
}
}
}
}

Remember the following two things: first,
Enabled
And
PopupMessage
Properties are saved in
ViewState
In this way, these values can always be consistent during the callback.
OnPreRender ()
Method, the keyword used for script block is text
Inclupopupmessage:
Add
UniqueID
Attribute. If a hard-coded keyword is used, only the first control can register its script block when multiple controls exist on the page. Therefore, only one pop-up dialog box is displayed. By using the script block keyword
UniqueID
To ensure that every instance of the control can obtain its script block.

Before registering a script block, the code first checks three conditions:

There is no script registered with the same keyword. This is of course impossible, because each control instance should have a UniqueID attribute value. However, you may wish to practice it first.
IsStartupScriptRegistered ()
Method, and then take the time to create and register the startup script.
The Enabled property of the control is True.
The page is not returned. This Code only allows the pop-up dialog box to be displayed when the page is loaded for the first time, rather than when the page is returned each time. We can also add more flexible features, that is, to add a Boolean attribute for the control, allowing users to specify whether to generate a pop-up dialog box during the Back-to-pass.
If the three conditions are met, the script is specified and
PopupMessage
The property value is inserted to an appropriate position in the script. Finally, call
Page
Attribute
RegisterStartupScript ()
Method to pass in the keyword and script code.

The PopupGreeting code can be obtained from the download provided at the end of this article. This download includes the Visual Studio. NET solution named ClientSideControlsAndTester, which contains two projects:

ClientSideControls, including the PopupGreeting Server Control
ClientSideTester, including an ASP. NET Web application designed to test ClientSideControls
The compiled Assembly name of the ClientSideControls project is
ClientSideControls. dll
. To use the PopupGreeting Server Control in your own ASP. NET Web application
ClientSideControls. dll
File to your Web application reference. Then, in the designer, right-click the Toolbox and select "Add/Remove Items..." (Add/delete Items), and select again
ClientSideControls. dll
File. In this way, a new project named PopupGreeting is added to the Toolbox. You can then drag the control from the Toolbox to the designer.

Figure 2 shows the screen snapshot of Visual Studio. NET After the PopupGreeting control is added to the Toolbox and added to the designer. The PopupGreeting control in the Toolbox is circled in red. The PopupGreeting output in the designer is circled in blue. You can view the attributes of PopupGreeting in the Properties pane on the right of the screen snapshot.

 

Figure 2: The PopupGreeting server control has been added to the ASP. NET Web form page.

Send HTML attributes of the Web Control of ASP. NET Server
As mentioned above, there are two ways to send client scripts through the server control:

Use the client script block
Using HTML element attributes
In the previous section, we discussed how to use
Page
Class
RegisterStartupScript ()
And
RegisterClientScriptBlock ()
Method to add a client script block to the ASP. NET Web page. In the last section, we learned how to add HTML element attributes to the HTML element of the server control.

Before starting, note that this method is generally only applicable
System. Web. UI. WebControls. WebControl
Server Control for class export, because the control exported from this class will send some HTML elements. Server controls that do not send HTML elements (such as the PopupGreeting Server Control in the previous section) do not need to write HTML element attributes because these controls do not write HTML elements at runtime.

WebControl
Class contains a method to add HTML element attributes to HTML elements sent by Web controls. This method is called
AddAttributesToRender ()
It only has one input parameter, that is
HtmlTextWriter
. To add HTML properties to a Web control, you can use
HtmlTextWriter
One of the following two methods:

AddAttribute ()
AddStyleAttribute ()
AddAttribute ()
Method
Title
,
Class
,
Style
And
Onclick
And other HTML attributes.
AddStyleAttribute ()
Used to add style settings to HTML elements, as shown in figure
Background-color
,
Color
And
Font-size
.

AddAttribute ()
There are several reload forms, but in the code, we will use the following forms:
AddAttribute (HtmlTextWriterAttribute, value)
. The first parameter, HtmlTextWriterAttribute, should be
HtmlTextWriterAttribute
Enumeration member. This enumeration includes images
Align
,
Bgcolor
,
Class
And
Onclick
. You can find the complete list in. NET Framework Class Library and HtmlTextWriterAttribute Enumeration. The value input parameter is used to specify the value assigned to a specific HTML attribute. Finally, if you want to add
HtmlTextWriterAttribute
Undefined HTML attribute in enumeration, which can be used
AddAttribute ()
Method substitution
AddAttribute (attributeName, value)
AttributeName and value are both strings.

To use this information, we create a server Web control as the confirmation button. The confirm button is a submit button. When you click this button, a pop-up dialog box is displayed asking whether you are sure you want to continue the operation. You can click Cancel without submitting a form. This function is particularly useful for buttons used to delete information, because end users (or website administrators) may accidentally click the mouse to delete entries in the database. If there is no chance to cancel, it will be very annoying.

To reduce the workload
System. Web. UI. WebControls. Button
Class to export the ConfirmButton Web control, because the class itself has completed all the heavy work involved in rendering the submit button. In the exported class, we only need to add an attribute so that you can specify the confirmation message and overwrite
AddAttributesToRender ()
Method, and add a property to process client events
Onclick
.

First, in Visual Studio. create a new Web Control Library project, or add a new Web Custom Control (Web Custom Control) in the ClientSideControls project ). The complete source code of the ConfirmButton class is as follows:

Using System;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. ComponentModel;

Namespace ClientSideControls
{
/// <Summary>
/// ConfirmButton abstract description.
/// </Summary>
[DefaultProperty ("Text "),
ToolboxData ("<{0}: ConfirmButton runat = server> </{0}: ConfirmButton>")]
Public class ConfirmButton: Button
{
[Bindable (true ),
Category ("Appearance "),
DefaultValue ("")]
Public string PopupMessage
{
Get
{
// Check whether this project exists in ViewState
Object popupMessage = this. ViewState ["PopupMessage"];
If (popupMessage! = Null)
Return this. ViewState ["PopupMessage"]. ToString ();
Else
Return "Are you sure you want to continue? ";
}

Set
{
// Specify the ViewState variable
ViewState ["PopupMessage"] = value;
}
}

Protected override void AddAttributesToRender (HtmlTextWriter writer)
{
Base. AddAttributesToRender (writer );

String script = @ "return confirm (" "% POPUP_MESSAGE % "");";
Script = script. Replace ("% POPUP_MESSAGE % ",
This. PopupMessage. Replace ("\"","\\\""));

Writer. AddAttribute (HtmlTextWriterAttribute. Onclick, script );
}
}
}

Note that,
ConfirmButton
Class is from
Button
Class. Because the Button class already contains all the attributes and methods used by the Button Web control, all we do is add attributes and methods to display a confirmation dialog box when you click the Button. Now we need an attribute, that is
PopupMessage
It is the message to be displayed in the confirmation pop-up dialog box. By default, this message is "Are you sure you want to continue ?" (Are you sure you want to continue ?) If you use ConfirmButton to confirm deletion, you may need to change the message to "This action will permanently delete the selected item. Are you sure you want to do this ?" (This operation permanently deletes the selected option. Are you sure you want to continue ?)

We only need to override one method, that is
AddAttributesToRender ()
. In this method, we only need to build
<Input>
Element
Onclick
The client JavaScript to be executed during the event, and
HtmlTextWriter
Object
AddAttribute ()
Method to add the JavaScript code. Note that
PopupMessage
Replace all double quotation marks in the attribute values with escape double quotation marks (that is
\"
). Note that, by default,
AddAttribute ()
The characters in the second parameter are HTML encoded. That is to say, if the ASP. NET Web page contains
PopupMessage
Property is set to "Do you want to continue ?" (Do you want to continue ?) ConfirmButton, the page will send the following HTML Tag:

<Input type = "submit" name = "ConfirmButton1"
Value = "Click Me! "Id =" ConfirmButton1 "onclick =" return confirm
(& Quot; Do you want to continue? & Quot;); "/>

If you are not familiar with JavaScript
Confirm (string)
Function. Note that this function only accepts one string parameter and displays a mode dialog box with a specific string. The dialog box contains two buttons: "OK" and "cancel ". If you click OK ",
Confirm ()
The function returns True. Otherwise, False is returned. Please note that,
Onclick
Event will return
Confirm ()
Function call result. When you click the submit button to submit a form
Onclick
If the event returns False, the form is not submitted. Therefore, you can use
Confirm ()
Function submission form. Related
Confirm ()
For more information, see Javascript Confirm Form Submission on the ASP Warrior website.

 

Figure 3: ConfirmButton in the action

ConfirmButton
Onclick
The embedded JavaScript is used in the event handler.
OnPreRender ()
Create a function in the client script block of the method, and then adjust
Onclick
Property to call this function.

Summary
In this article, we discuss two methods to insert client scripts through ASP. NET Server controls. The first method is to use the Page class
RegisterStartupScript ()
And
RegisterClientScriptBlock ()
Method to insert the client script block. The second method is to add a client script to the attributes of the HTML element. The latter overwrites
AddAttributesToRender ()
Method, and use
HtmlTextWriter
Of
AddAttribute ()
Method.

We also introduced two simple server controls in the article, both of which use the client scripts to improve their functions. The PopupGreeting control displays a mode pop-up dialog box when the page is loaded for the first time. The ConfirmButton Web control prompts you to confirm when you click the button to submit the form.

You can insert client scripts in your server control, which significantly improves user experience. The two server controls provided in this article are relatively simple and have no outstanding features in terms of availability and originality. MetaBuilders.com shows many functions implemented by inserting client scripts from ASP. NET Server controls. These functions will impress you. In MetaBuilders.com, you can find some server controls, some of which can automatically add focus to the text box, and some can pass entries between two drop-down lists, some can add or delete entries to the drop-down list, and some can display parent-child relationship data in a series of drop-down lists. The biggest benefit is that these controls are free of charge and include the complete source code.

Happy programming!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.