Execute client side jscript on page load based on server side logic

M

moondaddy

I'm using vb.net 1.1 and have an aspx page that I want some jscript to run
when the page loads on the client. Also I want this script to use logic
provided from the server in the Page_Load event. for example, if some
server side logic were true then when the page loads I would want the script
to change the text in a label in a different frame. If the server side
logic were false, then I would want to change the text in that same label to
something different again. I know I can generate jscript from the server
that would contain this logic by using something like this:

RegisterClientScriptBlock("clientScript", scriptString)
If (Not Page.IsClientScriptBlockRegistered("clientScript")) Then
Page.RegisterClientScriptBlock("clientScript", scriptString)
End If

But how can I get this code to run when the page loads on the client?

In the past I've used this line on the client to call a function when the
page loads, but I don't like it because it runs twice when the page loads:

document.onreadystatechange=myFunc;

Any good ideas for a better way to do this?
 
S

Steven Cheng[MSFT]

Hi Moondaddy,

From your description, you've registered a certain clientside script block
via the Page.RegisterClientScriptBlock() and you are wondering how to let
the script code executed when the page being loaded on clientside,yes?

I think you can make use of the body's onload client side event to execute
a certain clientside script function. For example:
<body onload="functionname()" >

Thus, a certain clientside javascript function will be called when the page
is loading.

Also, Instead of use Page.RegisterClientScriptBlock(), you can also put all
those different script functions( use for differernt logic on the
serverside code). Then you can use a hidden filed (<Input type=hidden
runat=server ..> ) to contain the flag which indicate which script function
to execute. Do you think so?

Please check out the above suggestions. Hope they're helpful. Thanks.


Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
K

Kevin Spencer

How about using Page.RegisterStartupScript()?

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 

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

Top