Insert client script from ASP.net server control (from MSDN Chinese Web site)

Source: Internet
Author: User
Tags continue html page html tags visual studio
asp.net| Insert | server | script | client | control | Chinese INTRODUCTION
Although technically speaking, Microsoft? All of the functionality of the ASP.net server control can be performed on the server side, but typically by adding client script can greatly enhance the usability of the server control. For example, the ASP.net validation Web control can perform all validation checks on the server side. However, for a newer browser, the validation Web control also sends client script to authenticate on the client. This means that users of these browsers can get a more responsive dynamic experience.

When developing ASP.net server controls, you may want to ask yourself how you can enhance availability by using client script. Once a viable solution is found, the other thing to do is to enhance the functionality of the server control so that it sends the appropriate client script.

asp.net server controls can send two types of client script:

Client script block
Client HTML Properties
Client script blocks are usually written in JavaScript, which typically contains functions that are executed when a particular client event occurs. Client HTML properties provide a way to associate client-side events with client script. For example, the following HTML page contains a client script block that contains a function named DoClick (). The page also contains a button (created from an HTML element) that is bound to the DoClick () function of the button's OnClick property. That is, as soon as the user clicks the button, the client code in the DoClick () function starts executing. In this example, a pop-up dialog box is displayed (Figure 1).


Figure 1 is clicked "Click me!" Screen shot of the HTML page when the button is clicked.



Figure 1: Click the "click me!" Pop-up dialog box displayed when a button is clicked

For client script in the above HTML page, there are a few noteworthy points to note. First, the client script block is included in the HTML annotation (). This is because if the script block is not placed in an HTML annotation, the old browser that does not recognize the script will display


In this code, the onclick= "Displaypopup ()" In the tag indicates that the JavaScript function Displaypopup () should run when the button is clicked.

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


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


Therefore, the RegisterStartupScript () method will be "; Scriptblock = Scriptblock.replace ("%%popup_message%%", this. Popupmessage); Page.registerstartupscript (Scriptkey, Scriptblock); } } } }


Remember the following two things: first, the Enabled and Popupmessage properties are stored in ViewState so that they can always be consistent at the time of the postback, and secondly, in the OnPreRender () method, the keyword used for the script block is the text Intopopupmessage: Adds the control's UniqueID property. If you use a hard-coded keyword, only the first control can register its script block when there are multiple controls in the page, so only one pop-up dialog box is displayed. By using UniqueID in the script block keyword, you can guarantee that each instance of the control gets its script block.

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

There are no scripts registered with the same keyword. This is of course not possible, because each control instance should have a UniqueID property value. However, you might want to practice using the isstartupscriptregistered () method first, and then take the time to create and register your startup scripts.
The control's Enabled property is True.
The page has not been returned. This code only allows pop-up dialogs to be displayed the first time the page is loaded, not every time the page is returned. We can also add a more flexible feature that adds a Boolean property to the control to allow the user to specify whether to generate a pop-up dialog box at the time of the postback.
If these three conditions are met, the script is specified, and the Popupmessage property value is inserted into the appropriate location in the script. Finally, call the RegisterStartupScript () method of the Page property and pass in the keyword and script code.

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

Clientsidecontrols, containing popupgreeting server controls
Clientsidetester, including a asp.net Web application designed to test Clientsidecontrols
The Clientsidecontrols project is compiled with an assembly name of ClientSideControls.dll. To use Popupgreeting server controls in your own ASP.net Web application, add ClientSideControls.dll files to your Web application's references. Then, in the designer, right-click the Toolbox (Toolbox) and select "Add/remove items ..." (Add/Remove items) and select ClientSideControls.dll file again. This adds a new item named Popupgreeting to the Toolbox (Toolbox). You can then drag the control from the Toolbox (Toolbox) to the designer.

Figure 2 shows a screenshot of Visual Studio. NET after the popupgreeting control has been added to the Toolbox (Toolbox) and added to the designer. The popupgreeting control in the Toolbox (Toolbox) is out with a red coil, and the popupgreeting output in the designer is out in blue, and you can view the properties of popupgreeting in the Properties pane on the right side of the screenshot.



Figure 2:popupgreeting Server control has been added to the ASP.net Web forms page

To send HTML properties for a asp.net server Web control
As mentioned, there are two ways to send client script through server controls:

By using client script blocks
Through HTML element properties
In the previous section, we explored how to use the RegisterStartupScript () and RegisterClientScriptBlock () Methods of the page class to add client script blocks to the ASP.net Web page. In the last section, we learned how to add HTML element attributes to the HTML element of a server control.

Before you begin, be aware that this method is typically applied only to server controls that are exported from the System.Web.UI.WebControls.WebControl class, because controls that are exported from this class send some HTML elements. server controls that do not send HTML elements, such as the Popupgreeting server control in the previous section, do not have to write HTML element properties because the controls do not write HTML elements when they run.

The WebControl class contains a method that adds HTML element attributes to HTML elements emitted by WEB controls. The method is called AddAttributesToRender (), and it has only one input parameter, that is, an instance of HtmlTextWriter. To add HTML properties to a Web control, you can use one of the following two methods of HtmlTextWriter:

AddAttribute ()
AddStyleAttribute ()
The AddAttribute () method is used to add HTML attributes such as title, class, style, and onclick to HTML elements. AddStyleAttribute () is used to add style settings to HTML elements, such as background-color, color, and font-size.

AddAttribute () has several overloaded forms, but in code we will use the following form: AddAttribute (HtmlTextWriterAttribute, value). The first argument, HtmlTextWriterAttribute, should be a member of the HtmlTextWriterAttribute enumeration. This enumeration contains items such as Align, bgcolor, Class, and Onclick. You can find the complete list in the. NET Framework Class Library,htmltextwriterattribute enumeration. The value input parameter is used to specify the values assigned to a particular HTML property. Finally, if you want to add an HTML attribute that is not defined in the HtmlTextWriterAttribute enumeration, you can use the alternative form of the AddAttribute () method AddAttribute (AttributeName, value), where the Both AttributeName and value are strings.

To use this information, we create a server Web control that acts as a confirmation button. The confirmation button is a submit button, and when the user clicks the button, a pop-up dialog box is displayed asking the user if they are sure they want to continue. The user can click Cancel to not submit the form. This feature is especially useful for buttons that delete information, because an end user (or site administrator) might accidentally click the mouse to delete an entry in the database, and it would be annoying if there was no chance of canceling it.

To reduce the workload, we export the ConfirmButton Web control from the System.Web.UI.WebControls.Button class because the class itself has done all the heavy work involved in rendering the submit button. In the exported class, we simply add a property so that the user can specify a confirmation message and then overwrite the AddAttributesToRender () method of the button and add a property to handle the client event onclick.

First, you create a new Web Control Library project in Visual Studio. NET, or you add a new Web custom controls in the Clientsidecontrols project (Web customization Control). The complete source code for the ConfirmButton class is as follows:

Using System; Using System.Web.UI; Using System.Web.UI.WebControls; Using System.ComponentModel; namespace Clientsidecontrols {//////ConfirmButton's summary description. [Defaultproperty ("Text"), ToolBoxData ("<{0}:confirmbutton runat=server>")] public class ConfirmButton: Button {[bindable (True), Category ("appearance"), DefaultValue ("")] public string Popupmessage {get {//check ViewState whether The Item Object popupmessage = this exists. viewstate["Popupmessage"]; if (popupmessage!= null) return this. viewstate["Popupmessage"]. ToString (); else return "Are your sure you want to continue?" The set {//Specifies 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); } } }
The first thing to note is that the ConfirmButton class is derived from the Button class. Because the button class already contains all the properties and methods used by the button Web control, all we do is add properties and methods to display a confirmation dialog box when the user clicks the button. Now we need a property, Popupmessage, which is the message to be displayed in the Confirmation pop-up dialog box. By default, this message is "Are you sure your want to continue?" (Are you sure you want to continue?) If you use ConfirmButton to confirm the deletion, you may need to change the message to "this action will permanently delete the selected item." Are you sure your want to doing this? " (This action will permanently delete the selected item.) Are you sure you want to continue? )

We simply cover one method, AddAttributesToRender (). In this method, we simply build the client JavaScript to execute when the onclick event triggers the element, and then add the JavaScript through the AddAttribute () method of the incoming HtmlTextWriter object. One thing to note about this approach is that you must replace all the double quote instances in the Popupmessage property value with escaped double quotes (that is, \ "). Also note that by default, AddAttribute () will HTML-encode the characters in the second argument. That is, if the ASP.net Web page contains the Popupmessage attribute, it is set to ' do your want to continue? ' (Do you want to continue?) ConfirmButton, the page will send the following HTML tags:


If you are unfamiliar with the confirm (string) function of JavaScript, note that the function accepts only one string parameter and displays a modal dialog box with a specific string. The dialog box contains two buttons: OK and cancel. If you click OK, the Confirm () function returns TRUE, otherwise it returns FALSE. Note that the OnClick event will return the result of the Confirm () function call. When a form is submitted by clicking the Submit button, if the button's OnClick event returns False, the form is not submitted. Therefore, the confirm () function can be used to submit the form only after the user has confirmed it. For more information about confirm (), see the Javascript confirm Form submission in the ASP Warrior Web site.



Figure 3: ConfirmButton in action

ConfirmButton uses embedded JavaScript in the button's OnClick event handler, and can also create a function in the client script block of the ConfirmButton OnPreRender () method, and then adjust the onclick property to call the function.

Summary
In this article, we explored two ways to insert client script through a asp.net server control. The first method is to insert the client script block using the RegisterStartupScript () and RegisterClientScriptBlock () methods of the Page class. The second method is to add client script to the attributes of the HTML element. The latter is accomplished by overriding the AddAttributesToRender () method of the Web server control and using the HtmlTextWriter AddAttribute () method.

We also introduced two simple server controls that use client script to improve their functionality. The Popupgreeting control displays a modal pop-up dialog box when the page is first loaded, ConfirmButton the Web control prompts the user for confirmation when the user clicks the button to submit the form.

You can insert client script in your own server control, which will significantly improve the user experience. The two server controls provided in this article are relatively simple and do not stand out from usability and ingenuity. Metabuilders.com demonstrates many of the features that are implemented with the ability to insert client script from ASP.net server controls to impress you. In Metabuilders.com, you can find some server controls that can automatically add focus to the text box, some can pass entries between the two Drop-down lists, some can add or remove entries from the list, or you can display the parent-child relationship data in a series of drop-down lists, and so on. The biggest benefit is that these controls are free and include the full source code.





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.