Saturday, April 3, 2010

Sliding error message

Among the frequent tasks in the ASP.NET applications is errors handling and displaying informational labels.


To display message, I use JQuery and particularly the slideDown function:



$(document).ready(function () {
if ($("#lblMessage").text().length == 0) {
return false;
}
if ($("#divMessage").length < 1) {
//If the message div doesn't exist, create it
$("body").append("<div id='divMessage' class='Message'><span id='spanMessage'<</span<<a href='#' class='close-notify'><img src='Styles/images/close.png' class='close' alt='close'/></a></div>");
}
//Else, update the text
$("#spanMessage").html($("#lblMessage").text());
//Fade message in
$("#divMessage").slideDown('fast');
//it's possible to Fade message out in 5 seconds for example
//setTimeout('$("#divMessage").hide("slow")', 5000);
$("#divMessage a.close-notify").click(function () {
$("#divMessage").slideUp("fast");
return false;
});
});

So i put my script inside JScript.js, after this point we need to perform some code in the Server code, so first, i add a Label in the MasterPage like this:

....<head runat="server">

<title></title>

<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />

<asp:ContentPlaceHolder ID="HeadContent" runat="server">

</asp:ContentPlaceHolder>

<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"> </script>

<script src="Scripts/JScript.js" type="text/javascript"> </script>

</head>

<body>

<form runat="server">

<asp:label id="lblMessage" ViewStateMode="Disabled" runat="server" />.....

In the child page, i perform some code wich cause an error :



public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!this.Page.IsPostBack) return;
int z = 0;
double a = 1 / z;
}
catch (DivideByZeroException ex)
{
Label lblMessage = Master.FindControl("lblMessage") as Label;
lblMessage.Text = String.Format("An unexpected error occurred : <br/>{0}", ex.Message);
}

}
}

And finally some style :



div.Message
{
margin:1px;
vertical-align: middle;
width: 97%;
position: absolute;
top: 0px;
border: 1px dashed #FF9900;
display: none;
background-color: #ffffcc;
font-family: "Segoe UI", Tahoma, Arial, Helvetica, sans-serif;
font-size: 11pt;
background-image: url(images/warning.png);
background-repeat: no-repeat;
padding-left:30px;
}

.close-notify {
white-space: nowrap;
float:right;
margin:2px;
}

.close
{
border-style: none;
}

#lblMessage
{
display: none;
}

It's look like this:



This article describe how we can display message errors into MasterPage using JQuery, this code is extensible for other cases. I hope this helps you out !



zip MessageError.zip - 133.6 Kio

No comments:

Post a Comment