I am a novice in .Net. Can anyone please help me by clarifying the below doubts... :cool:

How can we include a client side script like Javascript or VBscript in an ASP.Net page?

Can we have multiple <script> blocks in ASP.Net page?

Recommended Answers

All 5 Replies

ASP.NET produces HTML. The ASP.NET objects each "render" an HTML element, specific to the browser/OS/version. So whatever rules apply about mixing and embedding script with HTML applies as well.

The PAGE object has the "AddStartupScript" method, which doesn't do what you think it might (code the onload event of the body), but rather adds a script body to the end of the page.

Hi tgreer,

Thanx for the reply. What if i include some javascript in another script block without runat="server" attribute? Does that work as cliebtside script?

Yes, that works. You can also attach client-side event handlers with the "Add" method of an ASP.NET Server Object's "Attributes" collection.

So if you have a JavaScript function which you've placed in your document's "HEAD" section, named "myFunction()", and you want it to run when "myButton" is clicked, you can code:

myButton.Attributes.Add("onclick","<script>return myFunction()</script");

An important note: the "myFunction" JavaScript function should properly return "true" or "false". If "true", then the form submit occurs, and then the server-side "click" event handler, if any, will run. If "false", then the form submit is cancelled.

Hi aripaka,

To include a client-side script block from your asp.net code behind look into


This is very useful for scripts you expect to use in many aspx pages.

The following is an example C# method which registers a clientside javascript function to generate random numbers.

public static void RegisterRandomInt(Page page)
	if (page.IsClientScriptBlockRegistered("randomInt"))

	System.IO.StringWriter sw = new System.IO.StringWriter();
	HtmlTextWriter writer = new HtmlTextWriter(sw);
	writer.WriteAttribute("language", "Javascript");
	writer.WriteLine("function randomInt(lowInt, highInt)");
	writer.WriteLine("   return Math.floor(Math.random() * Math.abs((highInt+1)-lowInt)) + lowInt;");
	writer.WriteLine("  }");
	string script = sw.ToString();

	page.RegisterClientScriptBlock("randomInt", script);


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.