Insert a client script from the ASP. NET Server Control

Source: Internet
Author: User
Tags html comment

Prerequisites:This document assumes that the reader is familiar with ASP. NET.

Difficulty:2

Abstract:Although technically speaking, all functions of ASP. NET Server controls can be executed on the server side, 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:PopupgreetingA 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 javascriptConfirm ()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 containsDoclick (). The page also contains a button<Input>HTML element creation ).OnclickAttribute andDoclick ()Function binding. That is to say, you only need to click this button to start execution.Doclick ()Client in FunctionCode. 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>  

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, alert (String) The function is used to display a pop-up dialog box that contains messagesStringParameter. All HTML elements have several client attributes that can be bound to a client JavaScript code (for example,Onclick,Onmouseover,Onmouseout,OnfocusAndOnblurAnd so on ). For example, in the preceding HTML page,<Input>ElementOnclickProperty boundDoclick ()Function, so when you click this buttonDoclick ()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 useSystem. Web. UI. PageTo add the client script block to the ASP. NET web page. The two methods are as follows:Registerstartupscript ()AndRegisterclientscriptblock (). 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. Second ParameterScriptIs the client script to be inserted into the page, including<SCRIPT>. First ParameterKeyIs 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, andRegisterstartupscript ()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>  

In this Code,<Input>MarkedOnclick = "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 ()

DivisionRegisterstartupscript ()AndRegisterclientscriptblock ()In addition to methods,PageThe class also contains two auxiliary methods that are often used to send client scripts:

    • Isstartupscriptregistered (Key)
    • Isclientscriptblockregistered (Key)

As described aboveRegisterstartupscript ()OrRegisterclientscriptblock ()When you insert a client script block, a keyword is provided to uniquely identify the script block. Both methods accept one input (stringKey), And return a Boolean value to indicate whether the script block with the specified keyword has been added to the page. SpecificallyKeyThe script block has been registered. These methods 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. jsIs located in the ASP. NET web application.ProgramOfAspnet_client/system_web/Version NumberDirectory. Therefore, all these controls will send the same script block, which will be called inWebvalidation. jsFile to start the client verification process. To complete this process, these controls usePageClassRegisterclientscriptblock ()Method, and use keywordsValidatorincludescript.

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 twiceRegisterclientscriptblock ()OrRegisterstartupscript ()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 useIsclientscriptblock ()AndIsstartupscript ()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.ValidatorincludescriptThe 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 callIsclientscriptblock ()OrIsstartupscript ()Method to Determine whether to generate a client script. In the following section, we will see some examples. In these examples,Isclientscriptblock (),Isstartupscript ()Methods andRegisterclientscriptblock ()AndRegisterstartupscript ()Method.

Send client script blocks from ASP. NET Server controls

Remember,Registerstartupscript ()AndRegisterclientscriptblock ()The method isSystem. Web. UI. PageClass method. Fortunately, the two methods can be easily called from the ASP. NET Server Control, becauseSystem. Web. UI. ControlClass (all ASP. NET Server controls are exported directly or indirectly from this class) hasPageInstance referencePageAttribute, and thisPageThe 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 useOnprerender ()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. webcontrolExport. However, we want this classSystem. Web. UI. ControlClass export. Why? BecauseWebcontrolClass is used to support server controls that display HTML elements, whileControlClass 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, areSystem. Web. UI. webcontrols. webcontrolClass, and thoseNoControls that generate HTML elements, such as literal and repeater, areSystem. Web. UI. ControlClass.

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 bestSystem. Web. UI. ControlExport, not fromSystem. Web. UI. webcontrols. webcontrolExport.

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 addEnabledAttribute, becauseControlClass does not includeEnabledAttribute, which is implicitly composedWebcontrolUse the exported control .)

In addition to these two attributes, We need to overwriteOnprerender ()Method. Here, we need to callRegisterstartupscript ()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} opupgreeting runat = Server>
</{0} opupgreeting> ")] public class popupgreeting: system. Web. UI. Control {[Bindable (true), category (" appearance "),
Defaultvalue ("")] Public String popupmessage {get {// check whether this project object popupmessage = This. viewstate ["popupmessage"] exists in viewstate;
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 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;
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,EnabledAndPopupmessageProperties are saved inViewstateIn this way, these values can always be consistent during the callback.Onprerender ()Method, the keyword used for script block is textInclupopupmessage:AddUniqueidAttribute. 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 keywordUniqueidTo ensure that every instance of the control can obtain its script block.

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

    1. 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.
    2. The enabled property of the control is true.
    3. 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 andPopupmessageThe property value is inserted to an appropriate position in the script. Finally, callPageAttributeRegisterstartupscript ()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 isClientsidecontrols. dll. To use the popupgreeting Server Control in your own ASP. NET web applicationClientsidecontrols. dllFile to your web application reference. Then, in the designer, right-click the toolbox and select "Add/Remove items..." (Add/delete items), and select againClientsidecontrols. dllFile. 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 usePageClassRegisterstartupscript ()AndRegisterclientscriptblock ()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 applicableSystem. Web. UI. webcontrols. webcontrolServer 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.

WebcontrolClass contains a method to add HTML element attributes to HTML elements sent by Web controls. This method is calledAddattributestorender ()It only has one input parameter, that isHtmltextwriter. To add HTML properties to a web control, you can useHtmltextwriterOne of the following two methods:

    • Addattribute ()
    • Addstyleattribute ()

Addattribute ()MethodTitle,Class,StyleAndOnclickAnd other HTML attributes.Addstyleattribute ()Used to add style settings to HTML elements, as shown in figureBackground-color,ColorAndFont-size.

Addattribute ()There are several reload forms, but in the code, we will use the following forms:Addattribute (Htmltextwriterattribute,Value). The first parameter, that isHtmltextwriterattribute, It should beHtmltextwriterattributeEnumeration member. This enumeration includes imagesAlign,Bgcolor,ClassAndOnclick. You can find the complete list in. NET Framework class library and htmltextwriterattribute enumeration.ValueThe input parameter is used to specify the value assigned to a specific HTML attribute. Finally, if you want to addHtmltextwriterattributeUndefined HTML attribute in enumeration, which can be usedAddattribute ()Method substitutionAddattribute (Attributename,Value), WhereAttributenameAndValueAll are 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 workloadSystem. Web. UI. webcontrols. ButtonClass 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 overwriteAddattributestorender ()Method, and add a property to process client eventsOnclick.

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 ). Confirmbutton Class integritySource codeAs follows:

Using system; using system. Web. UI; using system. Web. UI. webcontrols; using system. componentmodel; namespace clientsidecontrols
{/// <Summary> /// summary description of confirmbutton. /// </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 object popupmessage = This. viewstate ["popupmessage"] exists in viewstate;
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,ConfirmbuttonClass is fromButtonClass. 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 isPopupmessageIt 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 isAddattributestorender (). In this method, we only need to build<Input>ElementOnclickThe client JavaScript to be executed during the event, andHtmltextwriterObjectAddattribute ()Method to add the JavaScript code. Note thatPopupmessageReplace 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 containsPopupmessageProperty 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 JavaScriptConfirm (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,OnclickEvent will returnConfirm ()Function call result. When you click the submit button to submit a formOnclickIf the event returns false, the form is not submitted. Therefore, you can useConfirm ()Function submission form. RelatedConfirm ()For more information, see JavaScript confirm form submission on the ASP warrior website.

Figure 3: confirmbutton in the action

ConfirmbuttonOnclickThe embedded Javascript is used in the event handler.Onprerender ()Create a function in the client script block of the method, and then adjustOnclickProperty 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 classRegisterstartupscript ()AndRegisterclientscriptblock ()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 overwritesAddattributestorender ()Method, and useHtmltextwriterOfAddattribute ()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!

Author Profile

Scott Mitchell has written five books on ASP/ASP. NET. He is the founder of the 4guysfromrolla.com website and has been engaged in Microsoft Web Technology Research for the past five years. Scott is ASP and ASP. NETCommunityA very active member who loves ASP and ASP. NET technologies and is very willing to help others understand these exciting technologies. For details about the DataGrid, datalist, and repeater controls, see Scott's book ASP. NET data Web controls kick start (ISBN is 0672325012 ).

Recommendation link:
    • Metabuilders.com client Web Control
    • . NET Framework class library, page. registerclientscriptblock method Technical Documentation
    • . NET Framework class library, page. registerstartupscript method Technical Documentation
    • Visual Studio magazine, implement client scripts
    • Building controls forum of ASP. NET forums
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.