DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

How To Embedding Javascript In Asp.Net

12.20.2011
| 1268 views |
  • submit to reddit
        There is one main class in the ASP.NET Framework included for working with Javascript: the ClientScriptManager class. This class is exposed by the Page.ClientScript property. The ClientScriptManager class has several useful methods for working with Javascript including:
 

RegisterClientScriptBlock():
Adds a script to a page right after the opening server-side <form> tag
 StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      RegisterClientScriptBlock(csname2, cstext2.ToString());
 

RegisterStartupScript():
Adds a script to a page right before the closing server-side <form> tag
 String cstext1 = "<script type=\"text/javascript\">" +
            "alert('Hello World');</" + "script>";
        RegisterStartupScript(csname1, cstext1);


RegisterClientScriptInclude():
Adds a reference to an external Javascript file
GetWebResourceUrl() - Returns the URL to a server-side resource
// Define the name, type and url of the client script on the page.
        String csname = "ButtonClickScript";
        String csurl = "~/script_include.js";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;

        // Check to see if the include script exists already.
        if (!cs.IsClientScriptIncludeRegistered(cstype, csname))
        {
            cs.RegisterClientScriptInclude(cstype, csname, ResolveClientUrl(csurl));
        }

<a href="http://www.java-forums.org/java-software/"><strong>Java Software</strong></a>