Skip to content
March 11, 2008 / kiranpatils

But how do I run JavaScript onLoad? with MasterPages

Today, I came across good situation after a page load i want to check that some Hidden variable contains what?. But how can i add javascript which runs Onload..some sharp people says that add it in javascript’s onLoad method. But hey sharp i am using Masterpages. So i can’t add it in Master page’s Body tag. Because so many of my pages referes that master page and don’t want that functionality for all pages i want on one specific page. Really good problem…don’t worry i have its solution also.

Problem

i want to call “LoadData” function of javascript OnLoad event of page with Master Page. I have my.js file which holds this function

Solution

ClientScript.RegisterStartupScript(this.GetType(), “LoadData“, “LoadData();”, true);

     Explanation:

ClientScript = Page.ClientScript Property Gets a ClientScriptManager object used to manage, register, and add script to the page. [http://msdn2.microsoft.com/en-us/library/system.web.ui.page.clientscript.aspx]

RegisterStartupScript : Registers the startup script with the Page object using a type, a key, a script literal, and a Boolean value indicating whether to add script tags.

ClientScriptManager..::.RegisterStartupScript Method (Type, String, String, Boolean) [http://msdn2.microsoft.com/en-us/library/z9h4dk8y.aspx]

This script will run after Page-Load event so [MSDN says if run before page_load] . But working for me

LoadData = Key to register function

LoadData();=function to call

true = Add script tag or not [NOTE: Must do this to true] .

Now put anything in LoadData() function under .js file that’s it.

Another Problem and its solution:

I want to take confirmation from User Yes/no and based on input i need to proceed but i forgot it how to do..the method is use confirm(“MESSAGE”) in javascript returns True/false. for example:

var answer = confirm(“YES/NO?”);
if(answer)
alert(“YES”);
else
alert(“NO”);

Enjoy!!

One Comment

Leave a Comment

Trackbacks

  1. asp.net, c#,javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: