2

I'm trying to update a JavaScript variable upon post-back. I was thinking of using the ClientScript.RegisterStartupScript function. It works on the initial page load but does not work on postback. I added the line below in the page_load function. I'm assuming whats happening is that if the key is added once it can not add it again the second time around. I have a master page and content page. I'm calling this from the content page.

ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Error !!!');</script>");

Is there a way of just calling a JavaScript function from the back-end?

Thanks

1
  • What are you trying to do? Maybe there are other alternatives Commented Apr 10, 2012 at 16:45

2 Answers 2

1

Try this way:

Syntax

   public void RegisterOnSubmitStatement (
        Type type,
        string key,
        string script

)

Usage

Placing this code on page load makes the script to fire on every submit click of the webform.

if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))
        {
            script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript", "alert('Submit Clicked')");
        }

Consider the below code

protected void Page_Load(object sender, EventArgs e)
    {    
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))
     {
          script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript", "return confirm('Are you sure to continue')");
     }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write("Form is Submitted.");
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I am using a grid and did not realize that RegisterOnSubmitStatement would be triggered as I change from one record to another. Each time I change from record to record it does a postback. Works great. Thank you.
1

You could put an asp:Literal inside a script block on your aspx page.

Then in your code behind, just put the variable assignment into the literal as text. It will get rendered as part of your javascript code.

2 Comments

Interesting, did not know you could do this. Thanks.
That's what Literal is for. Whatever you put inside it will be rendered exactly onto the page at exactly that position in the markup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.