JavaScript From PageLoad()?

F

Frank

Hi,



I am working with VS.NET 2005



Ultimately, I wish to call a JavaScript function from a .js file



In the Master page, I have:



<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Admin Pages</title>

<link href="common/css/admin_style.css" rel="stylesheet" type="text/css"
/>

<script language="JavaScript" src="common/js/global.js"
type="text/JavaScript"></script>

</head>

<body runat="server" id="body">

.

.

.

</body>

</html>



In the individual page code behind where I wish to call the js function, it
works if I use:



protected void Page_Load(object sender, EventArgs e)

{

try

{

string temp = "alert('Hello World!');";

HtmlGenericControl body =
(HtmlGenericControl)Master.FindControl("Body");

body.Attributes.Add("onload", temp);

}

catch (NullReferenceException x)

{

Response.Write(x);

}

}



But if I try to call a function from the js file like so:



protected void Page_Load(object sender, EventArgs e)

{

try

{

string temp = "TestJS();";

HtmlGenericControl body =
(HtmlGenericControl)Master.FindControl("Body");

body.Attributes.Add("onload", temp);

}

catch (NullReferenceException x)

{

Response.Write(x);

}

}



It fails. I don't get an ASP.NET exception, but rather a JavaScript error
which states it is expecting an object, but I can't figure out what object
it means. My js file looks like this:





// JScript File

function TestJS()

{

alert('Hello World!'};

}





The rendered html contains :

<body id="ctl00_body" onload="TestJS();">



Can anyone give some help please?



Frustrated to no end over what should be a simple operation!!
 
B

Brennan Stehling

Frank,

There is an ASP.NET feature to add scripts as you are trying to do with
a generic html control. Look for a method in
Page.ClientScript.RegisterClientScriptInclude(...).

Below is a code snippet which I use. You can also register a block as
well as other option. Be sure to always check if the script block is
already registered in case the event handler you place this in is
called more than once.

http://msdn2.microsoft.com/en-us/library/system.web.ui.clientscriptmanager_methods.aspx


#region " Methods "
private void RegisterScriptInclude(string key)
{
if
(!Page.ClientScript.IsClientScriptIncludeRegistered(key))
{
string url =
Page.ClientScript.GetWebResourceUrl(GetType(), Prefix + key);

Page.ClientScript.RegisterClientScriptInclude(typeof(EmbeddedScriptsManager),
key, url);
}
}
#endregion


You can actually get the full source for the project which includes
this method.

http://svn.offwhite.net/svn/SmallSharpTools.EmbeddedScripts/trunk/

I create a script manager for common JS libraries like Prototype and
Scriptaculous. It manages those scripts as embedded resources.

Brennan Stehling
http://brennan.offwhite.net/blog/
 
R

rb

I don't get it. Why don't you just do it as usual:

<script language="JavaScript" src="common/js/global.js"
type="text/JavaScript"></script>
<snip>
<body id="body" onload="TestJS();">

rb
 
B

Brennan Stehling

rb,

This technique generates those script tags. With ASP.NET you can build
a page with a series of User Controls which are fragments you can use
throughout the page. And a User Control does not have a HEAD tag at
all. It is like a Server-Side Include. You may have a User Control
represent a product display and have 6 products shown on the page. If
you had that control use a little Javascript you use this technique to
tell it to load the script just once by making sure it is not
registered before you do. Then your User Control can call methods in
that script files as needed.

For the sites I build with ASP.NET I take advantage of Master Pages
which act like a template for the whole website. The Master Page may
have User Controls for the navigation and footer areas. Then the Page
portion may use more User Controls.

I break things up into small User Controls as much as reasonable to
greatly simplify maintenance.

But if I do have a script I know I always wanted included for every
page I can still just place it in the Master Page header as a regular
script page.

Brennan Stehling
http://brennan.offwhite.net/blog/
 
R

rb

Thanks for the lecture but RegisterClientScriptInclude and UserControls
don't have much to do with Frank's question.

He works with master page and wants to use/call javascript function from
body.onload. He encountered a problem where by if he calls alert() from
onload everything seem to be fine. However, if he calls actual javascript
function he gets an error.

So, back to my "solution", since nothing seem to be dynamic, why not just
hardcode call to javascript from body.onload.

rb
 
F

Frank

Thanks for the responses so far everyone.

rb, the reason I don't just add <body id="body" onload="TestJS();"> to the
masterpage html, is because this is a function I want to execute on only
certain pages. If I out it into the Masterpage html, it will execute on all
pages.

And Brennan, I have seen a lot of code samoles that use the
Page.ClientScript.RegisterClientScriptInclude(...). you mentioned, but man,
what a pain. If I want to use the function on several different pages, I
themn have to script it in all the code behind pages and then I believe it
embedds the script in the resulting html which is ugly.

I simply wish to code the JS function once in the code behind and then
execute it from some individual pages within a site... there must be a way
to do this. I spent too much time on this already but the code I posted
seems the closest to what I am looking for, however as it is, it throws a JS
error and I am unsure how to resolve it. Thanks for any further effort or
consideration.


Frank
 
B

Brennan Stehling

Frank,

One of the ClientScript functions is RegisterStartupScript which does
run when the page is loaded.

http://msdn2.microsoft.com/en-us/li...lientscriptmanager.registerstartupscript.aspx

As for placing all of those code snippets all over the page, what I
like to do is place as much of the Javascript into a .js file and use
the RegisterScriptInclude function. Then in the places which do need
to call Javascript functions I add them as them as attributes.

Like the HyperLink control... It has an OnClick property but that is
for the server-side event handler. So I do this...

HyperLink1.Attribute["onclick"] = "runFunction();";

Regardless of how you load the Javascript file you will still need to
inline all of those methods calls in event handers.

I also make use of the commonly used and well-tested Javascript
libraries like Prototype and Scriptaculous. By leveraging them I write
less of my own code. And those libraries have already been developed
to work across multiple browsers and platforms. The problem with using
these libraries is that some require others so the dependencies can be
tough to manage over time. So I created this...

http://brennan.offwhite.net/blog/20...cript-in-aspnet-with-offwhiteembeddedscripts/

And since have renamed it and placed the code here...

http://svn.offwhite.net/trac/SmallSharpTools.EmbeddedScripts/

You could use that or create your own custom version of it to help you
manage your scripts.

Brennan Stehling
http://brennan.offwhite.net/blog/
 
B

Brennan Stehling

Frank,

Also, if you do get a problem with the methods not being immediately
available once the page is loaded you can wrapper you call with a
SetTimeout function with a very low timeout value. There is a bug in
some browsers where it does need that very slight delay.

I had this very problem the other day with Firefox while it was working
fine in IE. The timeout delay made it work.

Brennan Stehling
http://brennan.offwhite.net/blog/
 
F

Frank

OK, I got it...Thanks for all your help everyone:

<%@ Page Language="C#"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


public void Page_Load(Object sender, EventArgs e)
{
// 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));
}

//for the body onload functionality
string temp = "displaymessage()";
HtmlGenericControl body =
(HtmlGenericControl)Master.FindControl("Body");
body.Attributes.Add("onload", temp);

}


<html >
<head>
<title>ClientScriptManager Example</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<input type="text"
id="Message"/>
<input type="button"
value="ClickMe"
onclick="DoClick()"/>
</div>
</form>
</body>
</html>

This example requires a JavaScript file named Script_include.js with the
following contents:


function DoClick() {Form1.Message.value='Text from include script.'}


function displaymessage()
{
alert('Hello World!');
}


*** add <body runat="server" id="body"> to masterpage for the pageload
functionality
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top