Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
What are you trying to do? Maybe there are other alternatives –  MilkyWayJoe Apr 10 '12 at 16:45
add comment

2 Answers

up vote 1 down vote accepted

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.");
    }
share|improve this answer
    
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. –  Tesh Apr 10 '12 at 16:57
    
You're welcome.Glad that it helped you :) –  coder Apr 10 '12 at 16:58
add comment

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.

share|improve this answer
    
Interesting, did not know you could do this. Thanks. –  Tesh Apr 10 '12 at 16:57
    
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. –  SouthShoreAK Apr 10 '12 at 17:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.