Call JavaScript function from ASP.NET Content Page

One of the frequently asked questions by developers on the forums is How to call a JavaScript function from an ASP.NET Content Page, especially when the JavaScript is kept in a separate .js file. Let us see one of the ways:

Assuming you have a website with Master-Content page, create a folder called Scripts and place a JavaScript file in it. We will call it Alert.js. Add a function to the file that alerts a message, as shown below:

function callAlert() {
alert('Calling .js from Content Page');
}

The folder structure is as shown below:

Now let’s reference this file in our application. There are two common ways to do it: One way is to reference the .js file directly in your MasterPage. However the disadvantage is that if we use this approach, we would add a reference to the .js file for every content page in the application that uses the Master Page, even if we intend to use the script only in one Content Page. The second way is to add the .js file directly from the Content Page using the ‘RegisterClientScriptInclude’ as shown below:

protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("contentpg",
ResolveUrl(@"Scripts\Alert.js"));
// check if the start up script is already registered with a key
if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
{
// since it is not registered, register the script
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "callAlert();", true);
}
}

That’s it. Run the page and the alert will popup. Now right click the page and view the source and you should see the script reference added to the page.

Note: As you can see, this approach adds the JavaScript reference inside the <body>tag of the page and not the <head>.

If you liked this tip, make sure you read my articles

Calling JavaScript from ASP.NET Master Page and Content Pages - Part I

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: