C# 如何在 ASP.NET Web 应用程序中显示错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/651716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display an error message in an ASP.NET Web Application
提问by zohair
I have an ASP.NET web application, and I wanted to know how I could display an error message box when an exception is thrown.
我有一个 ASP.NET Web 应用程序,我想知道如何在引发异常时显示错误消息框。
For example,
例如,
try
{
do something
}
catch
{
messagebox.write("error");
//[This isn't the correct syntax, just what I want to achieve]
}
[The message box shows the error]
[消息框显示错误]
Thank you
谢谢
Duplicate ofHow to display an error message box in a web application asp.net c#
采纳答案by Canavar
Roughly you can do it like that :
大致你可以这样做:
try
{
//do something
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.
但我建议您定义自定义异常并将其扔到您需要的任何地方。在您的页面上捕获此自定义异常并注册您的消息框脚本。
回答by Jhonny D. Cano -Leftware-
The errors in ASP.Net are saved on the Server.GetLastError property,
ASP.Net 中的错误保存在 Server.GetLastError 属性中,
Or i would put a label on the asp.net page for displaying the error.
或者我会在 asp.net 页面上放置一个标签以显示错误。
try
{
do something
}
catch (YourException ex)
{
errorLabel.Text = ex.Message;
errorLabel.Visible = true;
}
回答by MStodd
All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.
您所需要的只是一个可以设置文本的控件,如果在回发期间发生异常,则需要一个 UpdatePanel。
If occurs during a postback: markup:
如果在回发期间发生:标记:
<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>
code:
代码:
try
{
do something
}
catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}