Call Javascript function from code-behind in C#.NET
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??
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>");
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.
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);
}
Try this
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SymbolError", "alert('error');", true);
Try to use the following:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AnUniqueKey", "alert('ERROR');", true);
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:
- Diffrent Methods to show msg box in Asp.net on server side - Coding Resolved
- Create a Message Box in ASP.NET using C# - Blog Sathish Sirikonda
精彩评论