Displaying client messages with Ajax Control Toolkit


Hi ,

I’ve not written for a (pretty) long time. Developing software is lovely but when it is done for making money and paying the bills it gets stinky! This is why I don’t find time to update the blog.

However in this post I am goanna write a helper class to show client messages in an Ajax enabled web application which exploits Ajax Control Toolkit. In this senario we have a web application that pages are blended with a master page. The master page hosts a ScriptManager to avoid putting one on each page. We will use ModalPopupExtender to show pretty client side messages! Why I say “pretty messages” is that we may show a message by injecting a <script>alert(‘…’);</script> message into the response stream, but I beleive it is too much simple and ugly! We also can use this method to do something in the modal window, like data entry or having more than two Yes and No buttons.

Well, first suppose we have a master page. To display messages we put a panel at the end of the master page’s code and decorate it in any way we enjoy the most! For example we may fill it with a table, one exclamation image and one button.

<asp:Panel runat=”server” ID = “_pnlClientMessage_” style=”display:none;” >

This panel has a style that makes it invisible. There is also a label that will be used to show the message.

<asp:Label runat=”server” ID = “_lblClientMessage_” />

There is also a button that will be used to close the modal popup.

<asp:Button ID=”btnCLose” runat=”server” Text=” OK “ CausesValidation=”false” />

Now we will put a ModalPopupExtender to show the modal message box:

<ajaxtoolkit:modalpopupextender ID=”mdlPopup” runat=”server”

TargetControlID=”btnShowPopup” PopupControlID=”_pnlClientMessage_”

CancelControlID=”btnClose” />

The properties we must set for modalpopupextender are :

1- TargetControlID , the ID of a control that will make the popup show. This contol is mandatory and is usually a button, therefore we will put a button on _pnlClientMessage_ panel and make it invisible:

<asp:Button id=”btnShowPopup” runat=”server” style=”display:none” />

As you may have noticed, we have not used Visible=”false”  to make btnShowPopup button and _pnlClientMessages_ panel invisible. The reason is that if  a control’s Visible property is set to false, it will not be rendered at all!

2-PopupControlID is the ID of a panel that will be showed when modal popup extender’s .Show() method is called.

3-CancelControlID is  the Id of a Button control that is placed on the panel and closes the modal popup if it is clicked!

The complete code is like bellow:

<asp:Panel runat=”server” ID = “_pnlClientMessage_” style=”display:none;” >

<asp:UpdatePanel ID=”_updClientMessage_” runat=”server” UpdateMode=”Conditional” >

<ContentTemplate>

<asp:Button id=”btnShowPopup” runat=”server” style=”display:none” />

<ajaxtoolkit:modalpopupextender ID=”mdlPopup” runat=”server”

TargetControlID=”btnShowPopup” PopupControlID=”_pnlClientMessage_”

CancelControlID=”btnClose” />

<asp:Label runat=”server” ID = “_lblClientMessage_” />

<asp:Button ID=”btnCLose” runat=”server” Text=” OK “ CausesValidation=”false” />

</ContentTemplate>

</asp:UpdatePanel>

</asp:Panel>

Please notice that I have used ModalPopupExtender control in the simplest way. You may configure and decorate it in many different styles, like making it movable. You may also have noticed that there is an UpdatePanel in the above code. This update panel is needed becuase we should call it’s Update method to update the panel’s content. Otherwise nothing will be shown.

Now we will write a class named ClientServices or ClientHelper, with a static method named ClientMessage. This method has two arguments:

1- A parameter of type Page. This parameter actually represents tha page from which the method is called.

2-A string parameter that represents the message to show.

This method first checks to see if the calling page has a master page. If it doesnt have a master page, the message will be sown with javascript’s alert function:

public static void ClientMessage(Page p, string message)

{

if (p.Master == null)

{

p.ClientScript.RegisterClientScriptBlock(p.GetType(),  System.Guid.NewGuid().ToString(),

string.Format(“<script>alert(‘{0}’);</script>”, message));

}

If the page has a master page, we will find the panel and the label control that we have provided for messaging and will set the label’s Text property :

else

{

Label _lblClientMessage_ = p.Master.FindControl(“_lblClientMessage_”) as Label;

_lblClientMessage_.Text = message;

We also have to find the update panel that I mentioned above and call it’s update method:

UpdatePanel upd = p.Master.FindControl(“_updClientMessage_”) as UpdatePanel;

upd.Update();

This will update the label’s text. Finally, we should fine the ModalPopupExtender and call it’s Show() method:

ModalPopupExtender extender = p.Master.FindControl(“mdlPopup”) as ModalPopupExtender;

extender.Show();

That’s it. Now anytime you want to show a modal message box, you can write a code like this:

try

{

// some code here

}

catch (Exception ex)

{

ClientServices.ClientMessage(Page, ex.message);

}

That’s it. This approach is extermly flexible so you can use it to gather some data from the end user, display a table and so on.

The image bellow is an example of such a client message:

By for now…

Ajaxism! Making your ASP.NET application Ajax enabled. (1)


Many ASP.NET developers believe that AJAX is equal to putting an update panel on a form and using it! I do not blame those programmers because Microsoft Ajax Extensions has come to ease the process of making a web site Ajax enabled and making Ajaxing procedures transparent. However, I believe every developer must know about the Ajax itself and its mechanism. Moreover, if we know about the drawbacks of using UpdatePanel, we might decide to write our own Ajax code.

What is AJAX?

The word Ajax is the abbreviation of Asynchronous Javascript and XML. In general, it means to use XML and Javascript in order to create interactive web applications. In the classic web model, the browsers posts some data to server and server sends a resul HTML code back to the browser. To view the results, your browser has to refresh the page. This makes the whole page content be transferred from server to client. Whilst in many cases only a very small part of the page must be refreshed. For example, suppose there are two DropDownList control on a page. One for countries (ddlCountry) and one for Provinces (ddlProvince). We need to refresh the ddlProvince items according the ddlCountry selected item. Should we post back the whole page to the server? Should we send the whole page from server to client? Using Ajax we just refresh ddlProvince and fill it with proper items.

In order to read a complete description of Ajax please refer to Wikipedia here:

http://en.wikipedia.org/wiki/AJAX

How to implement Ajax?

In Ajax world, everything is based on something named XMLHttpRequest. The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page’s Client-Side and Server-Side.

How to use it?

Inside IE, XmlHttpRequest is created via an ActiveX. However other borwsers, like FireFox, has an internal mechanism to instantiate a XmlHttlRequest object. Of course IE 7 provides a FireFox-like method to create XmlHttpRequest so that we do not have to check the browser type.

In IE:

var xmlHttp = null;

xmlHttp = new ActiveXObject(‘Microsoft.XMLHttp’);

Other Browsers:

var xmlHttp = null;

mlHttp = new XMLHttpRequest();

we can write a function ( in JavaScript) to do it:

var xmlHttp = null;

function CreateXMLHttpRequest()

{

if(window.ActiveXObject)

{

xmlHttp = new ActiveXObject(‘Microsoft.XMLHttp’);

}

else

{

xmlHttp = new XMLHttpRequest();

}

return xmlHttp;

}

As I mentioned before, you may use new XMLHttpRequest(); in IE 7+.

Now we are ready to send a request to Server and get a response from it. We may use this with XmlHttpRequest.Open method. This method takes three arguments:

1-‘GET’ or ‘POST’. Which approach is used to exchange data with server.

2- The URL on server.

3- True/False. Indicates is the communication with server Asynchronous or not. If you specify True, the open method will not wait for the response.

For instance, we may write this code:

xmlHttp.Open(‘GET’, ‘FetchUsers.aspx?ID=1’,true);

Afterwards we must wait for the response from the server. We are notified of a change in XmlHttp object with “onreadystatechange” event. This event belongs to XmlHttpRequest and we have to handle it. To do this, just write a JavaScript function and assign it to this event:

xmlHttp.onreadystatechange=update;

function update()

{

//some code here

}

What does update() function do? In such a function or better say such an event handler, we must check the value of readyState property. This property belongs to XmlHttpRequest and indicates what is going on! The possible values of this property are as follows:

0 or uninitialized

Object is not initialized with data.

1 or loading

Object is loading its data.

2 or loaded

Object has finished loading its data.

3 or interactive

User can interact with the object even though it is not fully loaded.

4 or complete

Object is completely initialized.

Well, needless to say that the server response is ready-to-use only if the readyState is 4.

Inside the Update() function we can do whatever we feel like, if readyState is 4:

if (xmlHttp.readyState ==4)

{

var msg=xmlHttp.responseText;

document.getElementById(‘lblHello’).innerText= msg;

}

Please look at the above code. The code shows that we have received the server response with responseText property. We may also receive an XML formatted response with responseXML. If you might have non-English characters in your response, I strongly recommend you to pass Data in XML format with utf-8 encoding.

The 2nd line above shows that the response has been assigned to innerText property. innerText is somehow equal to .Text property of a Label or Textbox control. You may use it if your response is Plain Text only. If your response is in html format you must assign it to innerHTML property.

That is it! You may write a small JavaScript function and assign it to any desired event, like onclick, ondblclick, onmouseover,on keyup and… to invoke your Ajax code.

However we must know that where the server response comes from? As the above example shows we get the response from FetchUsers.aspx. Whatever that FetchUsers.aspx writes into its Response object will be put in responseText property of XMLHttpRequest. By the way, the overhead of .aspx pages is too much I personally prefer to use Generic Handlers (.ashx). Generic Handlers are very flexible and lightweight . Therefore I will talk about them later on separate posts.

Let’s see the rest of the tutorial in action. I have written a sample code that you may download from HERE. This ASP.NET 2.0 website get’s your name and says you hello in an AJAX way 🙂 The source of JavaScript part of this implementation is here:

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>ASPGY.WORPRESS.COM</title>
<script type=”text/javascript” language=”javascript”>
var xmlHttp = null;
function CreateXMLHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject(‘Microsoft.XMLHttp’);
}
else
{
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
function process()
{
document.getElementById(‘lblHello’).innerText=”loading…”;
CreateXMLHttpRequest();
if (xmlHttp != null)
{
var uname=document.getElementById(‘TextBox1’).value;
xmlHttp.onreadystatechange=update;
xmlHttp.open(‘GET’,’process.ashx?name=’+uname, true);
xmlHttp.send();
}
else
alert(‘your browser does not support ajax’);
}
function update()
{
if (xmlHttp.readyState ==4)
{
var msg=xmlHttp.responseText;
document.getElementById(‘lblHello’).innerText=msg;
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<span style=”font-size: 16pt; color: #ff0066″><strong>AJAX Sample</strong></span><br />
<br />
<span style=”font-size: 9pt; font-family: Tahoma”>Enter name</span>:
<asp:TextBox ID=”TextBox1″ runat=”server” onkeyup=”process()”></asp:TextBox><br />
<asp:Label ID=”lblHello” runat=”server” Font-Names=”tahoma” Font-Size=”9pt” ForeColor=”Blue”></asp:Label></div>
</form>
</body>
</html>

You may also download a PDF version of this post HERE.