PassionateDeveloper
PassionateDeveloper

Reputation: 15138

Add OnLoad() in Page_Load()?

I have a few Database things to read in the Page_Load of my Asp.net page.

if (xxx == 1)
  //Add OnLoad("clock()")

How to do this? How to add a OnLoad-Method for a JavaScript clock in the page load method?

Upvotes: 2

Views: 7091

Answers (3)

Adam Spicer
Adam Spicer

Reputation: 2721

Register a startup script in the Page_Load. ClientScriptManager (http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx) or ScriptManager (http://msdn.microsoft.com/en-us/library/bb310408.aspx)... whichever is appropriate.

string clockStuff =
    @"function callClockFunction(){ 
    Sys.Application.remove_load(callClockFunction); 
    clock(); }
    Sys.Application.add_load(callClockFunction);";
ScriptManager.RegisterStartupScript(this, this.GetType(), "callClockFunction", clockStuff, true);

Upvotes: 1

Guffa
Guffa

Reputation: 700562

Use the RegisterClientScriptBlock method to add client code to the page:

Page.ClientScript.RegisterClientScriptBlock(
  this.GetType(),
  "onload",
  "window.onload = function(){ clock(); }",
  true
);

Upvotes: 2

Arnoud Kooi
Arnoud Kooi

Reputation: 1767

1st Make your body tag a servercontrol

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

2nd reference it like

if (xxx == 1)  
  BodyTag.Attributes.Add("onload", "clock()");

Upvotes: 4

Related Questions