Using jQuery to enhance ASP.NET AJAX progress indication
AJAX, ASP.NET, jQuery, UI By Dave Ward. Updated October 15, 2008Note: This post is part of a long-running series of posts covering the union of jQuery and ASP.NET: jQuery for the ASP.NET Developer.
Topics in this series range all the way from using jQuery to enhance UpdatePanels to using jQuery up to completely manage rendering and interaction in the browser with ASP.NET only acting as a backend API. If the post you're viewing now is something that interests you, be sure to check out the rest of the posts in this series.
In the spirit of Microsoft’s official embrace of jQuery last week, I’d like to show you an example of how easily you can add jQuery functionality to existing ASP.NET AJAX applications. jQuery allows you to achieve exceptional results with minimal difficulty, and integrating it with ASP.NET is not an exception.
My previous posts about jQuery have been somewhat lower level, incorporating JSON, web services, and the like. While these are important tools to have at your disposal, the realities of software development sometimes leave us scrambling for something quick and dirty.
In those situations, you may find yourself using the UpdatePanel.
To that end, I’m going to show you how easily you can use jQuery’s BlockUI plugin to display a modal progress indicator during an UpdatePanel’s partial postback.
Setting up a sample
To avoid performance consequences associated with the UpdatePanel, judicious use is key. However, if you find that you need access to the values of several controls on the page, an UpdatePanel may practically be the best way to get the job done.
Take this new customer form (left) for example:
<div id="EntryForm"> <label for="Name">Name:</label> <asp:TextBox runat="server" ID="Name" /> <label for="Address">Address:</label> <asp:TextBox runat="server" ID="Address" /> <label for="City">City:</label> <asp:TextBox runat="server" ID="City" /> <label for="State">State:</label> <asp:TextBox runat="server" ID="State" /> <label for="Zip">Zip:</label> <asp:TextBox runat="server" ID="Zip" /> <asp:Button runat="server" ID="Save" OnClick="Save_Click" Text="Add Customer" /> </div>
Assuming the form isn’t something expected to handle heavy usage, this is the type of thing that an UpdatePanel excels at. If the feature were to become popular and suffer from performance trouble, the UpdatePanel could always be refactored out in favor of a web service.
Styling the form
This CSS provides layout and basic styling:
#EntryForm { border: 1px solid #999; padding: 10px; width: 300px; } #EntryForm label { clear: both; float: left; margin-bottom: 5px; padding-right: 10px; text-align: right; width: 75px; } #EntryForm input[type=text] { float: left; margin-bottom: 10px; width: 150px; } #EntryForm input[type=button] { clear: both; margin-left: 85px; }
If you prefer using tables to lay out forms, that’s okay too. The jQuery technique described below will work equally well with either layout method.
Using the UpdatePanel to add asynchronicity
To asynchronously handle the server-side click event of the save button, add an UpdatePanel which specifies the save Button as an AsyncPostBackTrigger:
<asp:UpdatePanel runat="server" ID="up1"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Save" /> </Triggers> <ContentTemplate> <asp:Panel runat="server" ID="ConfirmSave" Visible="false"> <h3><asp:Literal runat="server" ID="CustomerName" /> added</h3> </asp:Panel> </ContentTemplate> </asp:UpdatePanel>
By positioning the UpdatePanel so that the partial postback is limited to refreshing only what is necessary, you can mitigate as much of its overhead as possible.
The Literal control allows us to provide contextual information to the user after the save completes. Implementing the server-side functionality for our fictitious form might look something like this:
protected void Save_Click(object sender, EventArgs e) { // Save the customer to your data store here. System.Threading.Thread.Sleep(2000); // Display the confirmation. ConfirmSave.Visible = true; // Customize the confirmation. CustomerName.Text = Name.Text; }
After the customer is saved, the confirmation message will be updated and the Panel control that contains it will be made visible.
You may be tempted to skip the Panel control and directly toggle the UpdatePanel’s visibility property instead. Unfortunately, that won’t work. An UpdatePanel is able to refresh its contents, but not itself.
Displaying the modal progress indicator with BlockUI
BlockUI’s functionality comes in two primary variations: blocking the entire page and blocking a particular element.
In this example, we’ll block the entry form’s container div, rather than the entire page. To invoke BlockUI on element(s), create a jQuery selector for the element(s) that you want to block and then call the .block() method on the resulting jQuery object.
To put this into action on our customer entry form, we need to add a client-side onclick handler to the save Button. To illustrate how effortlessly jQuery and ASP.NET AJAX integrate with each other, we can wire this event handler up in the Application.Init event:
Sys.Application.add_init(function() { // Allows the div.blockMsg style in CSS to // override BlockUI's defaults. $.blockUI.defaults.css = {}; // Add the BlockUI call as an onclick handler // of the Save button. $addHandler($get('Save'), 'click', function() { $('#EntryForm').block({ message: null }); }); });
If the jQuery-esque inline callback functions bother you, don’t worry. This style is interchangeable with what you’re used to seeing in most ASP.NET AJAX examples.
Using CSS to style the progress indicator
Next, let’s add a bit of custom styling to the BlockUI modal element. BlockUI’s defaults look pretty good, but we’ll need to change things around in order to get the progress indicator background image to display properly.
div.blockMsg { background-color: #fff; background-image: url(images/progress-indicator.gif); background-position: center center; background-repeat: no-repeat; border: 1px solid #ddd; height: 50px; width: 270px; }
Gotcha: the event stops here
Because BlockUI attempts to suppress form submissions as part of its blocking functionality, the save Button’s partial postback will also be blocked. To remedy this, we must set the Button’s UseSubmitBehavior property to false:
<asp:Button runat="server" ID="Save" OnClick="Save_Click" Text="Add Customer" UseSubmitBehavior="false" />
This will cause ASP.NET to render the Button with an onclick handler that executes __doPostBack instead of relying on HTML’s underlying form submission event.
Hiding the progress indicator afterward
BlockUI won’t automatically unblock our form after the partial postback completes. So, we’ll need some code to do that at the end of the UpdatePanel’s refresh.
There are several ways to accomplish this. In this limited example, adding the following code to our existing Application.Init handler is the simplest way:
// Get a reference to the PageRequestManager. var prm = Sys.WebForms.PageRequestManager.getInstance(); // Unblock the form when a partial postback ends. prm.add_endRequest(function() { $('#EntryForm').unblock(); });
We could use ScriptManager.RegisterStartupScript to emit the same unblock code from Save_OnClick, but I’d caution against doing that.
Needlessly mixing client and server side code entangles your presentation and logic together, leaving you with maintenance headaches. If you can avoid doing that, you’ll appreciate it later on.
Alternate event handler coding styles
I’ve been using anonymous functions to declare event handler callbacks inline, instead of the traditional route of using standalone functions. This is a choice of coding style, and is not functionally significant.
For example, this is equivalent to the previous click handler code:
Sys.Application.add_init(AppInit); function AppInit() { $.blockUI.defaults.css = {}; $addHandler($get('Save'), 'click', Save_Click); } function Save_Click() { $('#EntryForm').block({ message: null }); }
You could also use jQuery’s events instead of ASP.NET AJAX’s:
$(document).ready(function() { $.blockUI.defaults.css = {}; $('#Save').click(function() { $('#EntryForm').block({ message: null }); }); });
Many jQuery examples will use the latter method, so it’s important to understand that they are all roughly interchangeable.
Ultimately, the choice is completely up to you. What’s your preference?
Conclusion
I hope that this example has served to show just how easily jQuery allows you to add slick presentational effects to your ASP.NET AJAX applications.
Considering the amount of overlap between them, both frameworks do a great job of peacefully coexisting with each other. There’s no need to worry about combining the two right away, and then gradually beginning to enhance your existing ASP.NET AJAX functionality with jQuery.
If you enjoyed this example be sure to check out the followup post, Using jQuery to display a modal UpdatePanel confirmation, in which I describe how to implement a similar modal effect for the contextual confirmation Panel.
Try it for yourself
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.



BlockUI plug in from malsup is great but its missing one thing.. before the .Unblock() function i need to show a message in the modal less window and an Ok button to close the modal less window and return the web page opacity to normal…
i managed to do it but with a timer and the cursor was still showing Progress..
– one more thing .. it would be great to show how to integrate ASP .NET validation and jQuery, which to use and how they can work together (ex: having a validation group plus needing to do some work with jQuery before submitting of form)
thanks…
In my next post on the BlockUI subject, I’ll be covering exactly that. There is actually a way to accomplish it without a timer or any cursor trouble.
Hopefully, I’ll have time to get that posted early next week.
Hello Dave;
Thanks for the great post!! it is rock!
u mentioned regarding showing a message befor .UnBlock() method, adn you would publish a post concerning that, have u had a time to manage it?
thanks in advance.
regards.
You can find that post here: http://encosia.com/2008/10/11/using-jquery-to-display-a-modal-updatepanel-confirmation/
Dave;
thanks for quick response to my comment. the problem is that I dont use updatepanel on my page. I save my form by using page method instead of updatepanel. in this case, I used the .block() method, on the click event of my button, let’s say “btnSave”. then I unblock my data entry div on OnSuccess(result) method like that
function OnSuccess(result) {
if (result) {
$(‘#InsertEdit’).unblock({
onUnblock: function() {
document.getElementById(‘lblInfo’).innerHTML = “Saved”;
}
});
}
}
actually my real purpose is to set the innerHTML value of my lblInfo after a couple of seconds as empty.
what would u recommend for this scenario?
I hope I have expalined my purpose clearly.
thanks in advance.
best regards.
You can use setTimeout to run code after a delay. For example, to clear that after 5 seconds:
Hi,
Love your blog!
It would be nice if you could also upload the demo’s, so we don’t have to download and install them ourselves. Most of the time I get the full picture by reading the article, but that’s not always true and that’s where a demo could be useful…
Anyway, keep posting the good stuff!
tnx
One great post as always.
Keep on it.
Wow Dave, you always find the best plugins for JQuery. Thanks for the great find!
http://ajaxload.info/ is good for getting loading images
This is a great post, thanks a lot Dave!
We have published a free jQuery Animation library for ASP.NET developers to use. I use it for all my work and it saves a ton of work writing JavaScript. Not that writing jQuery isn’t easy, but its nice to be able to do the work on the server-side.
check it out: http://www.hushhushmedia.com/page/RIAnimation.aspx
nice feature and it works well for me …
But if i need to do the same for more than one text box … how cud i do it…
do i need to write all the functions again for each text boxes…
Refactoring the code for reuse is beyond the scope of this example. I’d suggest duplicating the code, analyzing what appears to be redundant, and then refactoring it to eliminate those redundancies.
This is my favourite work related website that I subscribe to! Keep up the good work, your tutorials and discussions are worth a lot!
It does not work on my machine, FireBug gives me some errors:
I am running ASP.NET 2.0 with AJAX 1.0 installed
This is usually either because your web.config doesn’t have the ASP.NET AJAX Extensions configured properly (see: http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx), or because you’re accessing the Sys object before it’s initialized (see: http://encosia.com/2007/08/16/updated-your-webconfig-but-sys-is-still-undefined/).
Hello Dave,
I need to implement an “ProgressIndicator” to show for all the AJAX operation on my web pages . Say I have 4 UpdatePanels on my page. “ProgressIndicator” will be shown for all of them ( when any of them perform any AJAX operation).
I will use the same jQuery block UI pluggin, infact I will use all the code here. Just one difference – Instead of writing an even handler on button click, I will write it on “startRequest” of PageRequest class.
Is it a good idea. ?
Thank You
Yes, that should work fine. You can block in the PageRequestManager’s BeginRequest event and then unblock in EndRequest.
If you want to block the UI for all AJAX requests, you can add a function at page load (!Page.IsPostBack):
Then any AJAX requests from ASP.NET will trigger blockUI.
Dave,
First off…love your posts. Tons of good info.
Now, I’m having an issue implementing your example in my real world application. I’ve got it working successfully in a Visual Studio project I created to get familiar with your code. However, I think my problem is coming from the authorization, authentication, and location settings in my web.config.
You see, I’m trying to use progress indication on a sign in page and I think maybe some of the javascript web resources are being blocked by the authorization level in the web.config.
Any ideas come to mind?
Thanks
I’d suggest loading the page and looking at it in Firebug’s “net” tab. Look for any resources that aren’t loading correctly (not showing a result code of 200 OK).
Everything was showing up as 200 OK in Firebug. In fact it worked in Firefox but was broken in ie (go figure).
Anyways, I found a solution by specifying
‘baseZ: 1000′ as one of the block parameters.
Thanks
Is using Sys.Application.add_init() required?
I’m just started to learn jQuery, and all the examples use the document.ready or just $(document)
to add event handler.
Is there a preferable choice to use either the jQuery eventhandler and $addHandler for ajax?
Thanks!
When dealing with UpdatePanels, it’s generally safest to use Application.Init instead of $(document).ready(). The DOM will often be “ready” before objects like Sys.Application and the PageRequestManager are instantiated and available. Using App.Init ensures that you get the timing right.
In this specific example, almost all of the code would work either way, except for the add_endRequest() call. Getting a reference to the PageRequestManager in $(document).ready() would probably lead to “Sys is undefined” errors.
For setting up event handlers, either should work. I personally prefer using jQuery for that, so that I can wire up events using selectors instead of ClientIDs (as you must use with $addHandler).
Dave,
Great post – this is exactly what I was looking for. However, I am running into a slight issue with it. I am trying to make the modal display whenever a .Net DropDownList (with AutoPostBack = true) changes. I got this to work the first time it changes, but if it changes again, the event doesn’t fire.
I think that the problem is with the $addHandler call itself, because I did a test where I just do an alert for the handler, and the same situation arises – it only works once.
I’m pretty new to building javascript events in this manner, so if you happen to know what my problem is here, I’d greatly appreciate it.
Okay, never mind my previous post – it was because the stupid code that I am working with has the entire user control inside the update panel, including where the javascript got included.
Adding the event handler again in the prm.add_endRequest call takes care of the issue.
However, now I found a new issue – Google Chrome doesn’t appear to like prm.add_endRequest. Anything I put in there, including the Unblock call, never fires. Does chrome not know how to handle that event?
There isn’t any Chrome-specific trouble with the ASP.NET AJAX events that I know of. Is it possible that you have a JavaScript error anywhere (which would cause the browser to not even execute that code, as you’re seeing)?
Thanks a lot for the effort. It is really appreciable. In most cases, such functionality is a must if we are updating using updatepanel.
Thanks again!
Hi Dave,
I am using Master page with .net validation controls…
In this case validation controls should come before progress indication…
I used your sample code, but the validation controls were invoked after progress indication…
Do you have any ideas (or a code example) how can I change the order of these events?
Thanks a lot!
Instead of triggering the progress indication with the Button’s click event, you could use the UpdatePanel’s BeginRequest event. This should only fire if the client-side validation routines have all passed (and Page_IsValid is true).
If your form is simple and partial postbacks are only raised by the event that requires progress indication, you could do it by changing the App.Init code like this:
If your page is more complex, you’d need to check sender._postBackSettings.sourceElement.id.
First, thank you Dave for the solution specified.
I know the date of the post but have a question:
By acting as mentioned, there is no problem and JQuery run perfect BUT I don’t know why via the Master Page, Progress Indicator and JQuery Schema not work…
Would you please helpl me?
Thank you
The Master Page will affect the ClientID of your elements. Use this instead of the above:
That’s not working…
Hello Jaza,
Move all your script in end of master page, As I have observed that, it is not working when your script is at top of master page. Please download sample from http://www.shailwx.com/2009/07/setup-your-website-for-using-jquery-and-jquery-plugins/
And try to play with it.
This is not really true from my experience. the update panel requires the script manager to be using before itself.
I have exactly the same problem. can you show me how did you fixed the problem. the code works like a charm without master page. but failed when using the with master page. I used Dave’s solution the error went away but the progress bar is not showing. Thank you so much.
Great post! I got it to work like a charm without using the master page. does the solution you provided here for the master page issue replace the whole Sys.Application.add_init routine? some how my error went away. but the progress image does not show up neither.
Thank you so much on helping us.
Ming
The code in my previous comment would replace the entire
$(document).ready()block. If you’re usingadd_init, then it would need to be updated like this:That assumes your controls are still named Save and EntryForm on your master page. If not, be sure to modify that accordingly.
It also assumes that this code is inline in an ASPX page, so the ASP.NET expressions can be resolved. If not, there are a variety of other ways to tame the ClientID issue (be sure to read the comments): http://encosia.com/robust-aspnet-control-referencing-in-javascript/
Dave,
I really appreciate that you take your time to help us to get the code to work after all these time.
Can you confirm that if my thought is correct? I should NOT put the default.js which contains Sys.Application.add_init() in the master page, right? I’m referencing the 2 jquery files in the master page file and the default.js in the page that is using master page uses this BlockUI plug in. Is it correct?
I updated your recommended code as followings and was able to move further but still having problem at the line in the Save_Click() function.
I’m using VS 2010 and I can step through the code in the updated default.js and jquery.blockUI.js. I got an error at this.style.zoom = 1 in the code shown bellow from jquery.blockUI.js.
Can you please take another look please? I felt that I’m really close. I can sent you my zipped project file if you do not mind.
Thank you so much!!!
The problem there is going to be that
< %= Save.ClientID %>and< %= EntryForm.ClientID %>can’t be resolved to their values in an external JavaScript file, because it doesn’t run through the ASP.NET engine like an ASPX file does. Take a look at some of the other suggestions in the comments on the robust ASP.NET control referencing post I linked earlier. Using a CSS class is one way, or if you don’t mind the performance hit, you can use the “ends with” selector.Dave,
Thank you for getting back to me. I finally got it to work with Shail’s example. the only thing is that his example blocks the whol screen instead of partial of the screen. I’ll try to get this one to work for me when i have more time to work on it. But it works for what i need to do at this time. Again, than you for your post.
My error is JScript runtime error: $.blockUI.defaults is null or not an obj at the line of $.blockUI.defaults.css = {};
That’s probably indicating that the BlockUI plugin’s JavaScript hasn’t been included on the page (or hasn’t been yet when that code’s running).
Hello,
May be you check check my web site for similar solution. The idea came from Dave’s this article.
Check the article here -
http://www.shailwx.com/2009/07/setup-your-website-for-using-jquery-and-jquery-plugins/
I am using Block UI to block UI for AJAX activity
Thanks
Thank you Dave & Shail
I got your way by some help.
Thank you
Hi,
Thanks for the useful post. New to jQuery and I just wanted to know what the best approaced for blocking out the whole page is? Currently I use the ID for the body tag (using CSS to set the height to 100%) but I assume that isn’t the recommended approach.
Thanks,
Markis
Assuming you’re using BlockUI, calling the $.blockUI() method without a selector will automatically expand the overlay to cover the full page.
Excellent, thanks. That worked. I am using the above example source code to work from. To center the div.blockMsg I am using the CSS properties left: 35%; top: 40%. Is this the preferred method?
Hi,
How does a work with BlockUI in this type of instance? Using UseSubmitBehavior=”false” doesn’t seem to work as it does with a normal , as detailed in the above example. My isn’t rendering the code-behind .cs onClick handler. The jQuery handler just loops and the code-behind .cs onclick handler never fires.
Thanks,
Markis
Try setting the BlockUI bindEvents setting to false.
Unfortunately $.blockUI({ message: null, bindEvents: false }); didn’t work. Any other ideas?
Got the asp:LinkButton to work by adding eval(this.href) to the handler. Any other ideas or a better solution is welcome.
You could probably also use __doPostBack(this.id, ”) to trigger a postback from the handler, if you want to avoid eval().
I am using a asp:Panel in a asp:UpdatePanel to feed in user controls at runtime based on various scenarios. How do I specify the trigger for a control that is nested in a separate control that is loaded at runtime?
You’ll need to add the trigger from code-behind, after you’ve loaded the dynamically loaded control. You can access an UpdatePanel’s Triggers collection imperatively there and add an AsyncPostBackTrigger to it that references the dynamically added control.
Thanks Dave! I have have added triggers programatically after the UC are loaded, and BlockUI with asp:Button is working as it should. However, I can’t get my javascript handlers to initiate with asp:LinkButtons (the opposite problem I had before when I couldn’t get my server side asp:LinkButton events to fire). When I click on a asp:LinkButton that is rendered within a user control it doesn’t activate the BlockUI. It is identically setup to the asp:Button. Any ideas?
Without seeing code, I would assume that your LinkButtons aren’t being successfully targeted by the $addHandler() call that wires up the BlockUI functionality. As complex as it sounds like your situation has become, you might be better off using a jQuery selector to add that handler to a variety of elements instead of targeting individual elements with $addHandler.
Interesting find: if I swap the handlers order of appearance around the LinkButton works (well, it initiates BlockUI but it doesn’t unblock – eval(this.href) isn’t working in the user control scenario) and the Buttons don’t. My .js file looks like this:
Sys.Application.add_init(function() {
$.blockUI.defaults.css = {};
$addHandler($get(‘AllCases_lbRefresh’), ‘click’, function() {
$.blockUI({ message: null, bindEvents: false });
eval(this.href); // this isn’t working anymore when using user controls
});
$addHandler($get(‘ClientProfile_btnSave’), ‘click’, function() {
$.blockUI({ message: null });
});
$addHandler($get(‘LawyerProfile_btnSave’), ‘click’, function() {
$.blockUI({ message: null });
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
$.unblockUI()
});
});
Your suggestion of “using a jQuery selector to add that handler to a variety of elements instead of targeting individual elements with $addHandler.” sounds good, but I’m afriad I don’t fully understand it. I’m very new to jQuery – do you perhaps have an example?
I think I am getting somewhere. Each of those controls (Buttons and LinkButtons) are embedded in separate user controls. If I set the handlers for each control in their respective user controls, and not using a separate .js file, the handlers work.
By using a single jQuery selector, I mean something like:
Or, if you tag all of those server controls with a CSS flag, you could use a single CSS-based jQuery selector.
Thanks Dave. That is much neater. This also seems to have resolved my issue of the BlockUI not detecting the partial postback for the LinkButton. This is working now too. However, it only works the first time.
E.g. I have a dropdownlist with a list of Provinces (States), and the click of the link button refreshes the data based on which Province is selected. The BlockUI kicks on the first click, but subsequent clicks don’t initiate BlockUI. Any idea why? (If I force a full postback using Response.Redirect(URL) it works – but that refreshes the page with the default items which is no good.)
If that refresh is a partial postback and the refresh replaces the markup for the BlockUI trigger, you’ll need to re-attach the handler after the partial postback (in EndRequest or pageLoad). Alternatively, you could use jQuery’s live() to wire up the handler instead of click().
Correction, the eval(this.href); actually is working because the code behind event is being fired (and I can see the page refreshing in the background). The UI just isn’t unblocking. I think because I am using a LinkButton (which use a javascript postback) the BlockUI isn’t detecting a partial postback so it never unblocks?
Still not sure why only the first handler is working and subsequent ones aren’t.
Thanks Dave! Upgrading my jQuery library to 1.3 and using .live(“click”, function() works perfectly.
I have validation setup on a webform using a combindation of asp:RequiredFieldValidators and asp:RegularExpressionValidators. I have a BlockUI handler configured for the Submit button, which is working nicely. However, if validation fails the message box pops up informing the user that validation has failed – when the OK button is clicked BlockUI kicks in and since it won’t cause a postback the UI is never unblocked. I currently have a timer set, which unlocks the UI, but this is a nasty work around. Is there a way to bypass BlockUI if validation fails?
Any idea how to do this?
Sorry, I missed this before somehow.
Probably the easiest fix would be testing the Page_IsValid global variable before blocking. ASP.NET’s client-side validation code maintains that based on the status on the client-side validation.
Depending on your page, the better solution may be to move the BlockUI code from the button’s click event to the PageRequestManager’s BeginRequest event. That should only fire after validation has succeeded. However, since that fires before every partial postback, you may need to test that the triggering panel is one that you do in fact want to cause a BlockUI modal.
Hi Dave,
You lost me. Can you explain it in a bit more detail please? I haven’t managed to get this to work. I am still using a timeout and the BlockUI is still firing when the page isn’t valid.
How do I test the Page_IsValid global variable from within my blockUI.js file? My blockUI.js currently looks like this:
Just add in a conditional based on that variable, like this:
That easy! Many thanks!
I spoke to soon. if (Page_IsValid) works for the button that has validatoin setup, but it has stopped BlockUI from firing on [some] other buttons. I actually have more than one control (buttons, links and linkbuttons) setup to initiate blockUI, some with validation but most without. Some are now just not firing at all.
e.g.
..
Help please?
It’s hard for me to help you debug that, not knowing the specifics (e.g. is validation on the page during every request, which elements trigger UpdatePanel refreshes, etc). I’d suggest stepping through that in Firebug, inspecting the DOM, and trying to get a sense for what’s going on in your particular situation.
Hi
Thanks for the excellent demonstration. I was trying to implement your code in one of my projects where I need to refresh the gridview based on the checkbox selection. I tried to hook up the event to selectindexchenged event of checkbox, but the jquery effect didnt work. Can you please suggest me something.
If you want the BlockUI modal to appear when you click a checkbox, you can use something like this to attach handlers to all their click events:
Thnx :)
Very cool post on adding JQuery functionality.
Thanks.
Hi, Amazing article and very well explained.
I have been trying really hard but cant get it to work for me for some reason
my page throws error
Sys.ArgumentNullException: Value cannot be null. Parameter name: element
[Break on this error] {name: “handler”, type: Function}
I am using a master pages, I tried using the tages like $addHandler($get(‘#’), ‘click’, function() {
$(‘#’).block({ message: null });
});
but not much use. Also my page has 2 AJAX modal popups. Is it messing up due to them ? The page works fine otherwise without including jquery reference. Is it a problem with using
Sys.Application.add_init(function()
?
ok, cant get my code to display properly however I used the control refernce inside scripts like ‘#’
Hey, it seems that in master pages the $get is causing problem. I solved my problem but in a bad sort of way by directly placing the full name inside script file. Have binged a lot but did not find a working solution. Can you advice a better solution then using this directly ?
Hey fellow, hello again. I’m sorry for buggin you again & again,
but blockUI is firing before the validation takes place. I have two validation groups on my form. How do I find which one raises the event and block the div only after the validation succeeded? I read your replies in the start but can’t figure it out yet.
Thanks, Mike.
Mike,
May be you would like to see this post of mine
http://www.shailwx.com/2009/07/setup-your-website-for-using-jquery-and-jquery-plugins/
Thanks Shail, your link is helpful. What you say about validation not firing and modal loading ?
Thanks Mike,
One of the reason for validation not firing is because validation JS written by ASP.Net is in that part of page, which is not updated with AJAX with UpDatePanel.
Also one very important thing to note, when you use jQuery with ASP.Net master page, always keep the script in bottom of your master page.
One more thing you should try, better do everything with jQuery. By that I mean write $(#yourbutton).Click(and your function here ).
Let me know if that works for you.
Shail
I have BlockUI setup in an ASP.net application on a asp:button and a asp:linkbutton on the same page that fire the same .net event handler. There is validaton setup on the form.
The button works perfectly, but the linkbutton still activates the BlockUI if validation fails, but only on the first click – on subsquently clicks both buttons work perfectly if validation fails, it’s only the first click for the linkbutton.
This is happening in FireFox and IE. Any ideas?
$(‘#NewCase_lnkSave’).live(“click”, function() {
if (Page_IsValid) {
$.blockUI({ message: ‘ ‘,
css: {
top: ’40%’, //($(window).height()- 100 ) / 2 + ‘px’,
left: ($(window).width() – 392) / 2 + ‘px’
}
});
var IE = /*@cc_on!@*/false;
if (IE) {
eval(this.href);
}
setTimeout($.unblockUI, 5000);
}
});
Please use this code (previous code didn’t include the button):
$(‘#NewCase_btnSaveValues, #NewCase_lnkSave’).live(“click”, function() {
if (Page_IsValid) {
$.blockUI({ message: ‘ ‘,
css: {
top: ’40%’, //($(window).height()- 100 ) / 2 + ‘px’,
left: ($(window).width() – 392) / 2 + ‘px’
}
});
var IE = /*@cc_on!@*/false;
if (IE) {
eval(this.href);
}
setTimeout($.unblockUI, 5000);
}
});
This is an awesome example you posted! I am very new to JQuery, but not ASP.Net.
Can you post the same example for use with ASP.Net Master pages and content pages. I have tried to implement this into my web application that has Master and content pages. I cannot get this to work!
Hello Ash,
Check this post at
http://www.shailwx.com/2009/07/setup-your-website-for-using-jquery-and-jquery-plugins/
I made an example for Master and content page after reading this revolutionary article from Dav.
Cheers !!
Shail:
I followed your post and downloaded your code as well. I am not following how to get this to work. Do you have an email address where I can send you my master and content page, so that you can tell me what I am doing wrong?
Thanks,
Ash!
The primary complication when using Master/Content pages is that the ClientIDs are going to be prefixed with something like ctl00. So, when you try to use this code:
It won’t find the “Save” button, because its ID has rendered as ctl00_Save instead. One option is to inject the rendered ClientID, like this:
Similarly, the jQuery selector for unblocking would need to be like this:
You can find more information on that here (be sure to see the comments for good alternative ideas too): http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/
Shail:
I sent you an email a few weeks ago (6/7/10), I have not heard back from you since? Can you help me out?
Ash.
Hello Ash,
Sorry I was not able to get back to you. I checked your code and found that you have just sent me 2 files, one master and one page. And these need many other files to work. So can you send me others ?
I will make a sample for you today and send you by evening.
Hello Ash,
I just sent you fixed and updated code, please check it and let me know if thats fine with you
Nice post. Using submit behaviour to false, what if a user wanted a client side script to execute after the save ? An alert or a jquery notifier. Submit behaviour to false won’t issue client side functions ?
You’d need to use RegisterStartupScript in your server-side event handler to emit the script you want to run after the postback completes.
Thanks Dave, you are right. Do you prefer placing the div outside the update panel for some specific ‘reason’ ? If yes, can you explain a little? What if we place the div inside the update panel. I think we would have trouble unblocking after partial postback. Mike.
UpdatePanels perform (slightly) better when their scope is limited to individual blocks of content that are meant to be updated individually. In this case, it’s also helpful because we’re able to reuse the UpdatePanel’s rendered div element as the modal’s container.
I had a tough time with unblocking a div placed inside the update panel because on asynch postback the contents would just get replaced & unblock would just occur in a snap & not with a fade as yours. Thank you for your nice articles & informative feedback, its a pleasure reading them.
Mike =)
Tip: To use this method with ASP.NET validation controls, you have to check the Page_ClientValidate function before running the .blockUI, like this…
// Add the BlockUI call as an onclick handler
// of the Save button.
$addHandler($get(‘Save’), ‘click’, function() {
if (Page_ClientValidate()) {
$(‘#EntryForm’).block({ message: ” ” });
}
});
If you are using validation groups, simply add the group as a parameter: Page_ClientValidate(‘Group1′)
Great article, love it replaces my own javascript implementation of this that I did a few years ago that has become bloated and unfriendly.
I do have a minor issue that I’m unable to track down.
What I’ve done is implemented your example but removed the panel where you display the save message and replaced it with a popup using jAlert.
Everything works great except that I can’t get the image (progress indicator) to appear, if I put text as the progress it will display but not the image. We are using cookiless so I thought maybe the session information was inteferring so I tried pulling the image from one of our public facing websites put still no go.
What could possibly be preventin the progress indicator image to just not display.
Thanks
I’m not familiar with that plugin, but it looks like you could do something similar by styling its .msg-box-cont container class with a background image.
Dave,
Thanks for the reply.
The jAlert plug in is for the pop-up at the end of “processing” to alert the user that the task is completed and is not part of the integration of the BlockUI example here.
My issue atm is that for whatever reason when I use the example of the BlockUI everything works great except that the image is not displaying, but when I run your example locally the image works.
I will track it down and let you know what exactly is interferring.
Thanks again
I want to do with tables … how would you do?
It should work with any type of element. Give your table an ID and then target that ID when you make the .block() call:
Dave,
To expand on my issue with the image not displaying, I have everything working but with a particulier issue with the image.
When I use
$('#LoadForm).block({ message: null });The image doesn’t display, but if I change the null to let’s say ‘Processing…’ the image displays.
$('#LoadForm).block({ message: 'Processing...' });Any idea?
It’s working so it’s not a biggie but it would be nice to know.
My guess is that the mix of CSS of your page isn’t allowing the div.blockMessage element to have a height when it’s empty. An uncleared float, maybe? But, when there’s text content in the element, that forces it to have height enough to display that text, which is enough for the background image to display as well.
@Dave Ward .. very good work.. can you help me to show progressbar before page load in asp.net
i.e i am loading listview on page with lot of data .. so i want to show 2-3 progressbar on page .. so one by one listview can be load … please reply me by mail
Thanks,
Hardik J. Desai
Give this a try: http://encosia.com/2008/02/05/boost-aspnet-performance-with-deferred-content-loading/
regards
I have tried to emulate this example by changing the calendar month of an object and I worked here as I am using
in webform
<div id="EntryForm"> <asp:Calendar ID="Calendar1" runat="server" BackColor="White" Width="100%" ForeColor="Black" Height="400px" Font-Size="X-Small" Font-Names="Verdana" BorderColor="White" Font-Bold="True" ShowNextPrevMonth="False"> <TodayDayStyle BackColor="#CCCCCC" Font-Size="X-Small"></TodayDayStyle> <DayHeaderStyle Font-Size="X-Small" Font-Bold="True"></DayHeaderStyle> <SelectedDayStyle ForeColor="White" BackColor="#333399"></SelectedDayStyle> </asp:Calendar> </div> <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton> <asp:UpdatePanel runat="server" ID="up1"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Save" /> </Triggers> <ContentTemplate> <asp:Panel runat="server" ID="ConfirmSave" Visible="false"> <h3><asp:Literal runat="server" ID="CustomerName" /> added.</h3> </asp:Panel> </ContentTemplate> </asp:UpdatePanel>in code c#
Greetings and thanks
Friend some example based on a master page and translated it does not work any ideas
What if want for every button in updatepanel ? at this case $get(‘#UpdatePanel1 input’) selector doesn’t work .
I appreciate any help
$getdoesn’t support a full range of selectors. it’s basically just adocument.getElementByIdshortcut. Use jQuery’s selector engine instead:How can I apply validation to some of the fields and show the progress if the form is valid only
That was very helpful to me. Thank you so much for sharing this.
By any chance do you know how can we achieve same functionality with JQueryUI Progressbar? Since i am already using JQueryUI i don’t want to add more plugin’s, any help would be much more appreciated.
$(document).ready(function() {
$.blockUI.defaults.css = {};
$(‘#Save’).click(function() {
$(‘#EntryForm’).block({ message: null });
});
});
jquery in update panel is only executed the first time