Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

ASP.NET: Register a javascript function

From Wiki

Jump to: navigation, search

Summary: Register a javascript function

There are a couple of ways to register javascript from your ASP.NET code behind pages. Firstly, if you want to register a function piece of javascript code that will run when the page loads, you can use the ClientScript.RegisterStartupScript method. Here's a simple example:

  1. ClientScript.RegisterStartupScript(Me.GetType(), "myjavascript", "alert('hello');", True)

Secondly, you may just want to register a function on the page so that other methods can call it. This is where the ClientScript.RegisterClientScriptBlock method comes in:

  1. Dim myFunction As New StringBuilder
  2. myFunction.AppendLine("function callMe() {")
  3. myFunction.AppendLine("alert('hello');")
  4. myFunction.AppendLine("}")
  5. ClientScript.RegisterClientScriptBlock(Me.GetType(), "myjavascript", myFunction.ToString, True)

In the above example, you can now call the javascript "callMe" function from other elements on your page.


This Hack is part of the ASP.NET Hacks collection

491 Rating: 3.5/5 (6 votes cast)