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
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 ownUpdatePanelwithUpdateMode="Always", which would require you to add saidUpdatePanelto 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 errorParentparameter to yourErrormethod, so it can add the error message as child control to that parent control.In your
catchblock, 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:Panelorasp: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
Literalchild control:Pass in the parent control: