2

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

1
  • Is this inside an update panel by chance? Commented Jul 16, 2010 at 13:26

6 Answers 6

9

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>");
Sign up to request clarification or add additional context in comments.

1 Comment

This works great! Thanks and the error stays on the same page.
2

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.

Comments

2

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);
    }

1 Comment

Am I missing something, why is this in a try/catch block?
1

Try this

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SymbolError", "alert('error');", true);

1 Comment

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.
0

Try to use the following:

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

Comments

0

I use this code in an asp.net project

 public void MsgBox1(string msg, Page refP)
{
    Label lbl = new Label();
    string lb = "window.alert('" + msg + "')";
    ScriptManager.RegisterClientScriptBlock(refP, this.GetType(), "UniqueKey", lb, true);
    refP.Controls.Add(lbl);
}

And when I call it, mostly for debugging

MsgBox1("alert(" + this.dropdownlist.SelectedValue.ToString() +")", this);

I got this from somewhere in the web, but was like a year ago and forgot the real original source

here are some related links:

Comments

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.