views:

85

answers:

5

Hi

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??

+4  A: 

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>");
GenericTypeTea
This works great! Thanks and the error stays on the same page.
Saher
+1  A: 

Try this

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SymbolError", "alert('error');", true);
BrunoLM
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
Works perfectly! Thanks
Saher
+1  A: 

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.

Fadrian Sudaman
+1  A: 

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);
    }
RandomNoob
Am I missing something, why is this in a try/catch block?
lark
I just copied and pasted OP's code
RandomNoob
A: 

Try to use the following:

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AnUniqueKey", "alert('ERROR');", true);
Giu