Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to call a javascript simple alert function when I catch an exception in my C# code as follows:

inside my function:

try
{
    //something!
}
catch (Exception exc)
{
    ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", 
     "<script type='text/javascript'>alert('Error !!!');return false;</script>");
}

Is there another way I can do this, because this doesn't show any alert boxes or anything??

share|improve this question
Is this inside an update panel by chance? – Nick Craver Jul 16 '10 at 13:26

5 Answers

up vote 9 down vote accepted

It's because you'll get the error along the lines of:

Return statement is outside the function

Just do the following, without the return statement:

ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", 
 "<script type='text/javascript'>alert('Error !!!');</script>");
share|improve this answer
This works great! Thanks and the error stays on the same page. – Saher Jul 16 '10 at 13:34

The above should work unless if it is inside update panel. For ajax postback, you will have to use ScriptManager.RegisterStartupScript(Page, typeof(Page), "SymbolError", "alert('error!!!')", true); instead.

share|improve this answer

Try this

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SymbolError", "alert('error');", true);
share|improve this answer
While in this case, RegisterClientScriptBlock will probably work because it's a simple alert, it's worth noting that this will place the JavaScript at the top of your page, so it may not be able to interact with stuff that hasn't loaded yet if you expect it to fire immediately. – Scott Anderson Jul 16 '10 at 13:31
Works perfectly! Thanks – Saher Jul 16 '10 at 13:32

Its the return, the below code works:

    try
    {
        throw new Exception("lol");
    }
    catch (Exception)
    {
        ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Error!!!');</script>", false);
    }
share|improve this answer
Am I missing something, why is this in a try/catch block? – tbranyen Jul 16 '10 at 13:36
I just copied and pasted OP's code – kd7 Jul 16 '10 at 14:25

Try to use the following:

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AnUniqueKey", "alert('ERROR');", true);
share|improve this answer

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.