Mad coder.
Mad coder.

Reputation: 2175

Run a javascript on postback in c#

I used the below manner to run a JavaScript upon postback and it worked fine for me.

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsPostBack)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'hidden';</script>");
        Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>function show()</script>");
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'visible';</script>");
    }
}

The above code worked fine and now I want to try something like below.

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsPostBack)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),"verify","<script type='text/javascript'>verify1();</script>");
    }
    else
    {
    }
}

in the above code verify1() is a JavaScript linked externally to ASPX page. I am unable to execute verify1() function using this code. And verify1() function works fine when placed as <body onload="verify1();"> Is there any syntax error(s) in my above code?

Upvotes: 0

Views: 3216

Answers (2)

Kishor
Kishor

Reputation: 201

this may help you,

Page.ClientScript.RegisterStartupScript(this.GetType(), "verify", "verify1()", true);

Upvotes: 1

jlew
jlew

Reputation: 10591

Maybe that script is being executed before verify1()'s function definition. By the time body.onload fires, the main page has completed parsing and all external scripts have been loaded, which is why it works in that scenario.

Can you use jquery? One option is to use jQuery's onload functionality, which won't be executed until everything is intialized:

$( function() { ...my startup code... });

Upvotes: 0

Related Questions