web 2.0

Show Loading Message in Asp.net AJAX

In this post, I will explain you how can we show Loading message in asp.net ajax without using Update Progress. Now some one may asked, why do I want to skip Update Progress ?

Well, there can be several reasons for this, fist of all you have to work on every single page, and on every update panel to get the update progress working.

There are basically three methods of meeting this requirement.

  1. Using Master Pages : A very smart way, but not all of us are using them .. right ?
  2. Extending Page Class  : A little harder but to me it is very elegant way.
  3. Extending Script Manager : Similar to the page class one, but implementation is comparatively simple.

The Basics:

Before I start with exploring the different approaches let me first create a ground by showing what things will be involve in creating a loading message.

I want the background to be grayed and displayed a simple loading text at the top, for that we need a style sheet, which will apply to the loading message div.  Create a stylesheet and call it style.css

.ModalProgressContainer
{
    z-index: 10005;
    position: fixed;
    cursor: wait; 
    top:0%; 
    background-color: #ffffff; 
    filter: alpha(opacity=50);
    opacity: 0.5;
    -moz-opacity: .5; 
    height: 100%;
    width: 100%;
    text-align: center; 
    
    } 
.ModalProgressContent
{
    padding: 10px; 
    border: solid 0px #000040; 
    font-weight: bold; 
    background-color:#ffffff;
    margin-top:300px;
} 

Now lets read and understand the following script.

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

// ----------------------------- //
// the below script will be saved in JS File, create a JS file and call it ajaxload.js and save the following script

function InitializeRequest(sender, args) {

    if (document.getElementById('ProgressDiv') != null)
       $get('ProgressDiv').style.display = 'block';
    else
        createContorl();
}

function EndRequest(sender, args) {

    if (document.getElementById('ProgressDiv') != null)
        $get('ProgressDiv').style.display = 'none';
    else
        createContorl();
}

function createContorl() {
    var parentDiv = document.createElement("div");
    parentDiv.setAttribute("class", "ModalProgressContainer");
    parentDiv.setAttribute("Id", "ProgressDiv");
 

    var innerContent = document.createElement("div");
    innerContent.setAttribute("class", "ModalProgressContent");
    var img = document.createElement("img");

    img.setAttribute("src", "/Images/Images/Loading.gif");

    var textDiv = document.createElement("div");
    textDiv.innerHTML = 'Loading....';

    innerContent.appendChild(img);
    innerContent.appendChild(textDiv);

    parentDiv.appendChild(innerContent);

    document.body.appendChild(parentDiv);

}

Notice,in the first three lines. We are getting the instance of PageRequestManager and then defining InitilizeRequest and EndRequest functions to display or hide the loading div. Where as, in createControl function we are simply writing DHTML, to be more specific there is no HTML of the loading div in our markup. So, we are writing that from JavaScript.

Also, note the that I have break down this script into two part by using comments. First is the declaration and second is definition of the functions.

note: The definition will take place on a seperate JS file where as the declaration need to be made in the page, under body markup.  Now we are all set to explore different approaches.

 

Using Master Pages :

A very simple approach, all you need to do is open your master page and paste the following lines in the head section.

<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="ajaxload.js"></script>

 

And in body, after form tag create a script section and paste the following JavaScript.

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

 

Notice it is the same declaration section which we have discussed above and that’s it you are done. All the content form of your web application should now display loading div on each partial postback.

 

Extending Page Class  :

For this, create a class file and call it ajaxPage and inherit it from System.Web.UI.Page and write the following code.

public class ajaxPage : Page
{
    protected override void OnLoad(EventArgs e)
    {
        //Include CSS File
        Page.Header.Controls.Add(new LiteralControl("<link href='style.css' rel='stylesheet' type='text/css' />"));


        //Include JS file on the page
        ClientScript.RegisterClientScriptInclude("ajaxload", ResolveUrl("~/ajaxload.js"));

        //Writing declaration script 
        String script = "var prm = Sys.WebForms.PageRequestManager.getInstance();";
        script += "prm.add_initializeRequest(InitializeRequest);";
        script += "prm.add_endRequest(EndRequest);";

        ClientScript.RegisterStartupScript(typeof(string), "body", script, true);

        base.OnLoad(e);
    }

}

 

Well, we have simply extend the System.Web.UI.Page into our own class and override OnLoad function to include the JS file and write the declaration markup.

Now, on the page code behind where you want to implement Loading message change the inherit namespace from System.Web.UI.Page to ajaxPage (make sure you namespace).

 

Extending Script Manager :

Now instead of extending page class we will extend Script Manager control and for that create a new class file and call it ScrtipManagerExt and write the following code.

public class ScriptManagerExt : ScriptManager
{
    protected override void OnLoad(EventArgs e)
    {

        //Include CSS File
        Page.Header.Controls.Add(new LiteralControl("<link href='style.css' rel='stylesheet' type='text/css' />"));

        RegisterClientScriptInclude(this, typeof(Page), "ajaload", ResolveClientUrl("~/ajaxload.js"));

        String script = "var prm = Sys.WebForms.PageRequestManager.getInstance();";
        script += "prm.add_initializeRequest(InitializeRequest);";
        script += "prm.add_endRequest(EndRequest);";

        RegisterStartupScript(this, typeof(Page), "ajaxtest", script, true);
        base.OnLoad(e);
    }
}

Almost the same thing we did in extend page approach, only the implementation will be change. Instead of using the old Script Manager we will use our new one. the include directive and markup will look like as below.

<%@ Register Assembly="Assembly" Namespace="namespace" TagPrefix="cc1" %>
<cc1:ScriptManagerExt ID="ScriptManagerExt1" runat="server">
</cc1:ScriptManagerExt>

 

That’s it we are done. I tried to make it simpler and show you every possible way I know of doing this task. Again, any approach selection will be on you and your project type. You can also download  the VS 2008 project file.

Comments

DotNetShoutout , on 7/12/2009 12:03:58 AM Said:

trackback

Show Loading Message in Asp.net AJAX

Thank you for submitting this cool story - Trackback from DotNetShoutout

pete United States, on 7/12/2009 11:25:06 PM Said:

pete

wow,  I keep forgetting how complicated microsoft ajax is.   Here is JQuery ajax.  Note the few lines of code.  Note how the code is near self documenting.

            // Block UI, pop I am workig message
            $(document).ready(function() {
                $.blockUI({ message: $('#YourDivWithWorkingMessage'), css: { width: '275px' } });
             });
            
                                
            // build args and call Controller/Action
            var dataToSend = BuildObject()
            var methodAction = 'YourController/YourAction';
      
        $.ajax({
                data: dataToSend,
                dataType: 'html',
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $.unblockUI();
                    var errorObj = JSON.parse(XMLHttpRequest.responseText);
                    $('#LabelInErrorDiv).html(errorObj.message);
                    $.blockUI({ message: $('#ErrorDivForAjaxError), css: { width: '275px' } });
                },
                success: function(data) {
                    $.unblockUI();
                    $('#YourDivToPutResultIn).html(data);
                    },
                url: methodAction
            });

9eFish , on 7/13/2009 11:23:57 AM Said:

trackback

Show Loading Message in Asp.net AJAX

9efish.感谢你的文章 - Trackback from 9eFish

LG India, on 7/13/2009 5:11:31 PM Said:

LG

Hey Usman, Good post.I think it will be good to include the loading image in the stylesheet class itself.

Agha Usman Islamic Republic of Pakistan, on 7/20/2009 3:44:11 PM Said:

Agha Usman

@LG

Yep !! we can do that too, your option is good but I just want to make it simple so that the beginners can understand it ...

Regcure Review United States, on 9/12/2009 8:45:26 PM Said:

Regcure Review

Hi,
I was looking for that solution nearly all day.Can i copy this article into my blog?If you  are agree,we can exchange useful articles in the future?

Best Regards,
Chris

lace wigs United States, on 11/3/2009 6:13:15 PM Said:

lace wigs

Before u start with exploring the different approaches let me first create a ground by showing what things will be involve in creating a loading message.

extra income, United States, on 11/4/2009 3:44:01 AM Said:

extra income,

Dude.. I am not much into reading, but somehow I got to read lots of articles on your blog. Its amazing how interesting it is for me to visit you very often.

DigBands United States, on 11/5/2009 5:46:53 AM Said:

DigBands

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

dentist charlotte nc United States, on 11/7/2009 2:33:42 AM Said:

dentist charlotte nc

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Thanks!

Lyrics United States, on 11/8/2009 4:22:11 AM Said:

Lyrics

I completely agree with the above comment, the internet is with a doubt growing into the most important medium of communication across the globe and its due to sites like this that ideas are spreading so quickly.

tomato juicer United States, on 11/13/2009 6:48:54 PM Said:

tomato juicer

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.

north phoenix apartments United States, on 11/14/2009 6:26:58 PM Said:

north phoenix apartments

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

Coffee Bean Grinders United States, on 11/16/2009 6:32:49 AM Said:

Coffee Bean Grinders

I personally have embraced the new technologies and the CMS platforms, I think the new tools only make the web designs better. I am glad that new technologies are coming out in web design that make things easier, improved, and better looking for design.

income drawdown United States, on 11/20/2009 4:22:57 AM Said:

income drawdown

Thank you for the sensible critique. Me & my neighbour were preparing to do some research about that. We got a good book on that matter from our local library and most books where not as influensive as your information. I am very glad to see such information which I was searching for a long time.This made very glad Smile

cheap replica handbags Hong Kong S.A.R., on 11/23/2009 6:57:40 PM Said:

cheap replica handbags

excellent quality brand cheap replica handbags  lots of people like them.
http://www.goodshotsale.com

Forex ECN Broker United States, on 12/12/2009 3:14:48 AM Said:

Forex ECN Broker

the blog is absolutely Fantastic and Helpful!!!

pandora jewelry People's Republic of China, on 12/14/2009 2:46:23 AM Said:

pandora jewelry

Good post.I think it will be good to include the loading image in the stylesheet class itself.

IT contractor accountant United States, on 12/15/2009 8:15:06 AM Said:

IT contractor accountant

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

chapel hill real estate United States, on 12/18/2009 2:05:03 AM Said:

chapel hill real estate

This is very well explained. I like the way you have written this article. I am sure a lot of people will benefit from it. Thanks!

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading