创建并显示动态错误消息(在 UpdatePanel 内不起作用)
我的 Web 表单继承了一个名为 MyPageMain
的类,该类继承了 System.Web.UI.Page
并位于 App_Code
文件夹中。
在这个 MyPageMain
类中,我创建了这个方法,用于记录和输出异常(错误消息):
public string Error(Exception pException, string pFriendlyMessage)
{
using (BusError erro = new BusError())
{
int? errorId = //HERE Routine to log the error;
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
writer.AddAttribute(HtmlTextWriterAttribute.Class, "erroMain");
writer.RenderBeginTag(HtmlTextWriterTag.Div); //<div>
writer.RenderBeginTag(HtmlTextWriterTag.P); //<p>
writer.Write(pFriendlyMessage);
writer.RenderEndTag(); // </p>
writer.RenderBeginTag(HtmlTextWriterTag.Small);
writer.Write("Event tracker:");
writer.Write(errorId);
writer.RenderEndTag();
writer.RenderEndTag(); // </div>
Console.WriteLine(stringWriter.ToString());
}
}
}
然后,当页面上出现一些异常时,我调用它,如下所示:
Protected void btnLoad_Click(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
//Loading some data here.
}
catch (Exception ex)
{
Error(ex, "Unexpected error trying to load data.");
}
}
This is bulding OK, but不起作用...我认为原因之一可能是整个事情都在 UpdatePanel 内。关于如何开展这项工作有什么建议吗?
这个 Console.Writeline
适合我想做的事情吗?这适用于 UpdatePanel 吗?
已经尝试过 Response.Write(...) ,它确实有效。但不在 UpdatePanel
内
My web forms inherits a class called MyPageMain
, which inhertis System.Web.UI.Page
and is located on the App_Code
folder.
In this MyPageMain
class I created this method, to record and output Exceptions (error messages):
public string Error(Exception pException, string pFriendlyMessage)
{
using (BusError erro = new BusError())
{
int? errorId = //HERE Routine to log the error;
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
writer.AddAttribute(HtmlTextWriterAttribute.Class, "erroMain");
writer.RenderBeginTag(HtmlTextWriterTag.Div); //<div>
writer.RenderBeginTag(HtmlTextWriterTag.P); //<p>
writer.Write(pFriendlyMessage);
writer.RenderEndTag(); // </p>
writer.RenderBeginTag(HtmlTextWriterTag.Small);
writer.Write("Event tracker:");
writer.Write(errorId);
writer.RenderEndTag();
writer.RenderEndTag(); // </div>
Console.WriteLine(stringWriter.ToString());
}
}
}
Then, when there is some exception on the page, I call it, like this:
Protected void btnLoad_Click(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
//Loading some data here.
}
catch (Exception ex)
{
Error(ex, "Unexpected error trying to load data.");
}
}
This is bulding OK, but doesn't work... I think that one of the reasons may be the fact that the whole thing is inside an UpdatePanel. Any suggestions on how to make this work?
Is this Console.Writeline
suitable for what i'm trying to do? Is this going to work on UpdatePanels?
Already Tried with Response.Write(...)
and it does work. But not inside an UpdatePanel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
当您使用
UpdatePanel
时,您只能在从该面板触发的异步回发期间更新面板内的内容,因此您的错误消息必须出现在UpdatePanel
内的某个位置。 (也就是说,除非您在其中一个UpdatePanels
上设置UpdateMode="Always"
,否则其内容会在每次异步和完整回发时更新。但这并没有帮助除非您将错误消息放入其自己的UpdatePanel
中并使用UpdateMode="Always"
,这将要求您将所述UpdatePanel
添加到每个我明白这是页面。 不是您想要执行的操作。)以下示例将在
UpdatePanel
顶部添加错误消息。您需要将
Control errorParent
参数添加到Error
方法中,以便它可以将错误消息作为子控件添加到该父控件。在您的
catch
块中,只需传入您希望显示错误消息的任何容器控件即可。该控件必须是接受子控件的容器,因此它必须是呈现为或
标记的内容,例如
>asp:Panel
或asp:UpdatePanel
。在下面的示例中,您可以使用
errorParent.Controls.Add(errorControl)
在UpdatePanel
底部显示错误消息,或使用AddAt()
具有不同的索引。只要确保索引始终适用于每个页面即可。获取父控件并添加新的
Literal
子控件:传入父控件:
When you use an
UpdatePanel
, you can only update content within the panel during an async postback triggered from that panel, so your error message will have to appear somewhere within theUpdatePanel
. (That is, unless you setUpdateMode="Always"
on one of yourUpdatePanels
, then its content is updated on every async and full postback. But that doesn't help you here unless you put your error message in its ownUpdatePanel
withUpdateMode="Always"
, which would require you to add saidUpdatePanel
to every page. I understand this is not what you want to do.)The following example will work to add the error message at the top of the
UpdatePanel
.You will need to add a
Control errorParent
parameter to yourError
method, so it can add the error message as child control to that parent control.In your
catch
block, just pass in whatever container control where you want the error message to appear. That control must be a container to accept child controls, so it has to be something that renders as a<div>
or<span>
tag, like anasp:Panel
orasp:UpdatePanel
.In the example below, you could use
errorParent.Controls.Add(errorControl)
to show the error message at the bottom of theUpdatePanel
, or useAddAt()
with a different index. Just be sure that index will always work on every page.Take a parent control and add a new
Literal
child control:Pass in the parent control:
由于您的 Error 方法返回字符串,因此您可以返回错误消息并显示它。
将 Literal 放入您的 UpdatePanel 中(也许在 MasterPage 中,因此您不必为所有 40 个或更多页面编写它)。当抛出异常时,使用 Error 方法处理它,并将返回的消息设置为 Literal。
Console.WriteLine 在 ASP.NET 中不可用。请改用 Debug.WriteLine。它将写入 VisualStudio 中的输出窗口。
Since your Error method returns string, you can return error message and display it.
Place Literal in your UpdatePanel (maybe in MasterPage, so you do not have to write it for all 40 or more pages). When exception is thrown, handle it with your Error method and set returned message to Literal.
Console.WriteLine is not usable in ASP.NET. Use Debug.WriteLine instead. It will write to Output window in VisualStudio.
许多答案都围绕着这个问题。
Console.WriteLine
是一个用于为控制台应用程序(命令行)输出一行文本。这是一个网络应用程序。因此,您可以使用Response.Write
将字符串吐出到响应流或设置页面上已有的 Literal 控件的文本并将其设置为可见(默认隐藏)。由于我自己完全错过了
UpdatePanel
细节,这里有一个替代解决方案来弥补它。我的示例使用隐藏的div
和一些 jQuery,通过使用 ScriptManager 控件将文本注入到UpdatePanel
外部的div
中。根据按钮的go_Click
处理程序方法的条件,它将使用 jQuery 显示或隐藏错误消息,该消息在UpdatePanel< 时注入到页面服务器端/code> 的更新。
请注意,在使用 AJAX 时,使用 ScriptManager 的函数来注册 JavaScript 而不是 Page.ClientScript 至关重要。使用后者不会将 JS 添加到页面。
页面标记
页面代码隐藏
Many of the answers are dancing around the issue.
Console.WriteLine
is a command used to output a line of text for a Console application (command-line). This is a Web app. So, you either useResponse.Write
to spit a string out to the Response stream or set the text of a Literal control that is already on the page and set it to be visible (default hidden).Since I myself completely missed the
UpdatePanel
detail, here's an alternate solution to make up for it. My example uses a hiddendiv
and some jQuery through the usage of the ScriptManager control to inject text into adiv
that is outside theUpdatePanel
. Based on the conditions of thego_Click
handler method of the button, it'll show or hide an error message using jQuery that gets injected into the Page server-side at the time of theUpdatePanel
's update.Note that it is critically important to use the ScriptManager's functions to register JavaScript rather than Page.ClientScript when using AJAX. Using the latter won't add the JS to the page.
Page markup
Page code-behind
我觉得还没有人真正回答整个问题,所以让我尝试一下。
可能不会,除非您只想在调试时将调试信息显示在输出窗口中。有些人喜欢继续向控制台输出信息,即使在发布版本中也是如此,因此如果您想对错误执行此操作,这是一个有效的选择,但您还应该向用户显示友好的错误消息和/或记录某种持久性的错误(例如日志文件)。上面的所有答案都建议您向用户显示一些错误通知的方法。
如果您的触发器等设置正确(我们知道它们是因为您说您能够命中Console.WriteLine 断点),则没有理由不这样做。我想知道您的控制台输出是否工作正常,但您在错误的位置寻找它?在 Web 应用程序的典型配置中,它应该出现在您用于调试的 Visual Studio 实例的输出窗口中。
至于我认为您要问的问题的建议,即“如果加载更新面板的内容时出错,如何让错误消息显示在更新面板中?”。 ..
我建议采用类似于上述 nekno 提案的方法。您可以动态添加一个控件,您可以在更新面板请求处理期间将其文本设置为错误字符串,或者您甚至可以在页面上设置一个最初隐藏/折叠的控件,该控件仅设置为在发生错误时可见。我更喜欢后一种方法,因为它更易于维护。您可以从 ASPX 页面的标记/显示视图完全控制错误标签的外观和感觉。
I feel like nobody has actually answered the entire question yet, so let me try.
Probably not, unless you just want debug information to appear in the output window while debugging. Some people like to keep outputting info to the Console, even in a release build and so if you want to do that with your errors, it's a valid choice, but you should also be showing a friendly error message to the user and/or logging the error to some kind of persistence (eg. log file). All of the answers above are suggesting ways for you to show some notification of the error to the user.
There is NO reason why it shouldn't if your triggers and the like are set up properly (and we know they are because you said that you're able to hit the Console.WriteLine breakpoint). I wonder if your Console output is working fine but you're looking for it in the wrong place? In the typical configuration for a web application, it should appear in the Output window of the Visual Studio instance you're using to Debug.
As to a suggestion for what I think you're asking, which is "how do I get my error message to appear in the update panel if there's an error loading the content for that update panel?"...
I would suggest an approach similar to nekno's proposal above. You can either dynamically add a control whose text you can set to be the error string during update panel request processing or you can even have an initially hidden/collapsed control on the page, which is only set to be visible in the case of an error. I'd prefer the latter approach because it's more maintainable. You can completely control the look and feel of the error label from the markup/display views of your ASPX page.
LoadData() 方法运行后,您是否在 UpdatePanel 上调用 .update() ?我认为 UpdatePanel 不会自动触发,除非回发来自其内部。
例如:
更新:通过注册这样的触发器,我能够让
Response.Write()
在 UpdatePanel 中工作
用于将创建错误的按钮。Are you calling .update() on your UpdatePanel after your LoadData() method runs? I think the UpdatePanel won't automatically fire unless the postback originates from inside it.
Ex:
Update: I was able to get
Response.Write()
to work in an UpdatePanel by registering a trigger like this<Triggers><asp:PostBackTrigger ControlID="btn1" /></Triggers>
for the button that will create the error.您是否正在尝试记录错误或显示错误?如果您尝试显示它们,您应该:
在母版页上,创建一个将显示错误的位置(可能在导航栏下方或底部附近:
每次收到错误时,您都可以按原样调用错误函数,但您可以在其中添加一个标签,而不是使用 Response.Write() 或 Console.WriteLine() 写出文本:
这将帮助您显示错误,但此时 AJAX 仍然是一个问题。你有两个选择:
由于更新面板更新其他更新面板,您可以将更新面板包裹在
cphError
周围,这样您的 AJAX 调用仍将更新该区域OR:您可以使用
ClientScript.RegisterStartupScript
创建错误标签(这。仅当您没有静态错误消息点时,此方法才是更好的选择)Are you trying to log errors or display them? If you are trying to display them, you should:
On your masterpage, create a spot where your errors will be displayed (maybe below your navigation bar or near the bottom:
Everytime you get an error, you can call your error function as is, but instead of writing out the text with Response.Write() or Console.WriteLine(), you can add a label in there:
This will help you out with displaying the error, but AJAX will still be a problem. At this point, you have two options:
Since update panels update other update panels, you can wrap an update panel around
cphError
, this way your AJAX calls will still update that areaOR: You can can use
ClientScript.RegisterStartupScript
to create the error label. (This method is only preferable if you do not have a static error message spot)在master上放置一个Panel,使用AjaxToolKit中的modalpopupextender对其进行扩展。出现错误时,将字符串编写器的内容写入面板中的标签,例如 Label lbl = (Label)Master.FindControl()
lbl.text = StringWriter.ToString();
// 现在访问模式弹出窗口
AjaxControlToolkit.ModalPopupExtender MPE = (AjaxControlToolkit.ModalPopupExtender)Master.findControl("");
// 并显示它
MPE.Show();
模态框需要一个隐藏按钮作为其目标控件,但不需要用户输入。我使用以下代码在页面上完成此操作:
祝你好运
Place a Panel on the master, extend it with the modalpopupextender in the AjaxToolKit. When the error is raised, write the contents of string writer to a label in the panel E.g. Label lbl = (Label)Master.FindControl()
lbl.text = StringWriter.ToString();
// Now access the modal popup
AjaxControlToolkit.ModalPopupExtender MPE = (AjaxControlToolkit.ModalPopupExtender)Master.findControl("");
// and show it
MPE.Show();
The Modal will need a hidden button to use as it's target control, but it will not require a user's input. I accomplish this on the page with the following code:
Good luck
我认为 Console.WriteLine 不适用于 ASP.NET 应用程序,并且我认为在更新面板中您可以简单地触发抛出新异常(友好的错误消息),它将出现在警报框中。
I think Console.WriteLine don''t work on asp.net application and i think inside an update panel you can simple fire the throw New Exception( the friendly error message) and it will appear in an alert box.