Methods for adding client scripts to the ASP. NET page

Source: Internet
Author: User

It mainly includes the following three methods:
Statically include client scripts in script blocks that contain code or reference JavaScript (. js) files using the include feature. With this option, you can insert client scripts that do not require dynamic creation or additional AJAX functions provided by Microsoft AJAX Librarc y in the script block or JavaScript file.

  • Use the ClientScriptManager class to dynamically create client scripts and add them to ASP. NET web pages. If the script dependency to be created is only available at runtime, use this option.

  • If you plan to use ASP. NET's AJAX function, you can use the ScriptManager Server Control to manage client script files. The ScriptManager Server Control also ensures that the browser has loaded the Microsoft AJAX Library before running your script.


    ClientScriptManager


    The ClientScriptManager class is used to manage client scripts and add them to Web applications. You can obtain a reference to the ClientScriptManager class from the ClientScript attribute of the Page object.

    By adding scripts to the HTML Tag of a webpage, you can add client scripts to the webpage in declarative mode. However, in some cases, you need to dynamically add client scripts. To dynamically Add a script, use the RegisterClientScriptBlock method, RegisterClientScriptInclude method, RegisterStartupScript method, or RegisterOnSubmitStatement method based on the time and method you want to add the script.


    publicvoid Page_Load(Object sender, EventArgs e)  {    // Define the name and type of the client scripts on the page.    String csname1 = "PopupScript";    String csname2 = "ButtonClickScript";    Type cstype = this.GetType();    // Get a ClientScriptManager reference from the Page class.    ClientScriptManager cs = Page.ClientScript;    // Check to see if the startup script is already registered.if (!cs.IsStartupScriptRegistered(cstype, csname1))    {      String cstext1 = "alert('Hello World');";      cs.RegisterStartupScript(cstype, csname1, cstext1, true);    }    // Check to see if the client script is already registered.if (!cs.IsClientScriptBlockRegistered(cstype, csname2))    {      StringBuilder cstext2 = new StringBuilder();      cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");      cstext2.Append("Form1.Message.value='Text from client script.'} </");      cstext2.Append("script>");      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);    }  }

    The following describes the methods:

    Method

    Description

    RegisterClientScriptBlock

    Add a script block to the top of the page. Create a script as a string and pass it to the method. The method then adds the script to the page. You can use this method to insert any script into the page. Note that the script may be rendered to the page before all elements are completed. Therefore, you may not be able to reference all elements on the page from the script.

    RegisterClientScriptInclude

    Similar to the RegisterClientScriptBlock method, this method adds a script block that references an external. js file. Include files added before any other dynamically added scripts; therefore, you may not be able to reference certain elements on the page.

    RegisterStartupScript

    Add a script block to the page, which is executed before the onload event of the page is triggered after the page is loaded. This script is generally not created as an event handler or function; it usually only contains the statement to be executed once.

    RegisterOnSubmitStatement

    The script executed by adding the onsubmit event on the response page. This script is executed before the submission page. You can cancel the submission.


    You can use the ClientScriptManager class to call the client callback when you expect to run the server code from the client without sending back. This is called an out-of-band callback to the server. In the client callback, the client script function sends an asynchronous request to the ASP. NET webpage. Modify the normal lifecycle of a webpage to process callback. Use the GetCallbackEventReference method to obtain a reference to the client function. When this function is called, it starts a client callback for server-side events.
    ASP. NET web page for client callback
    <%@ Page Language="C#" AutoEventWireup="true"   CodeFile="ClientCallback.aspx.cs" Inherits="ClientCallback" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML   1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;publicpartialclass ClientCallback : System.Web.UI.Page,     System.Web.UI.ICallbackEventHandler{    protected System.Collections.Specialized.ListDictionary catalog;    protected String returnValue;    protectedvoid Page_Load(object sender, EventArgs e)    {        String cbReference =            Page.ClientScript.GetCallbackEventReference(this,            "arg", "ReceiveServerData", "context");        String callbackScript;        callbackScript = "function CallServer(arg, context)" +            "{ " + cbReference + ";}";        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),            "CallServer", callbackScript, true);        catalog = new System.Collections.Specialized.ListDictionary();        catalog.Add("monitor", 12);        catalog.Add("laptop", 10);        catalog.Add("keyboard", 23);        catalog.Add("mouse", 17);        ListBox1.DataSource = catalog;        ListBox1.DataTextField = "key";        ListBox1.DataBind();    }    publicvoid RaiseCallbackEvent(String eventArgument)    {        if (catalog[eventArgument] == null)        {            returnValue = "-1";        }        else        {            returnValue = catalog[eventArgument].ToString();        }    }    public String GetCallbackResult()    {        return returnValue;    }}

    This web page simulates a database query to determine the supply or inventory quantity of a series of products (such as monitors and keyboards.



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.