Executing Javascript as soon as UpdatePanel trigger is fired - c#

I have found out it is possible to execute javascript after an UpdatePanel has updated it's contents, but is it possible to execute javascript as soon as the trigger is fired?
I could probably hack some messy javascript, but I was wondering if ASP.NET had any 'inbuilt' functionality?

Quote from MSDN - endRequest Event:
The endRequest event is raised after an asynchronous postback is finished and control has been returned to the browser.
In other words you can attach a javascript handler function to the beginning and ending of a partial postback (when the update panel updates).
In the example on the page, you can see that the handler is attached using the PageRequestManager:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)
For reference purposes:
beginRequest - Start of the Request.
endRequest - When the request is completed.

UpdatePanel usage implies full page life cycle to be triggered again, so you should be able to catch the document ready, in jQuery terms, like this:
$(function() {
// Handler for .ready() called.
});
see here: http://api.jquery.com/ready/

I guess there are a few options here you could obviously do something like the following.
<div id="Container" onclick="__doPostBack('UpdatePanel1', '');">
But any of the page life cycle events could be used here is an excellent resource on what and when everything gets called.

Related

RegisterStartupScript method - page OnLoad event

Look at the documentation for both ScriptManager's and ClientScript's RegisterStartupScript method. In the former case, it says:
The script block that is rendered by the RegisterStartupScript method
executes when the page finishes loading but before the page's client
onload event is raised. Startup script blocks are located at the
bottom of the rendered ASP.NET page just before the tag.
https://msdn.microsoft.com/en-gb/library/bb310408(v=vs.110).aspx
Whereas, in the latter:
The script block added by the RegisterStartupScript method executes
when the page finishes loading but before the page's OnLoad event is
raised.
https://msdn.microsoft.com/en-gb/library/z9h4dk8y(v=vs.110).aspx
So in the second case, they mention the OnLoad method that raises the Load event of the Page (which is a part of the ASP.NET page lifecycle), not the client's page onload event.
Is it just a mistake in the documentation? Javascript runs on client's side, and that's after all the page lifecycle has completed and the final page has been sent to the client).
Yes you are right, the latter information is a mistake.
The script block is rendered in the pages render event and it's executed by the browser on client side right on parsing.

How do you call OnPageIndexChanging from Javascript?

I have code that when a user wants to page through a GridView, it asks them (using a JavaScript confirm) if they want to save the data from the grid.
So, I'm able to get the confirm to work (with the code-behind saving function), but I'm noticing that it's not firing the OnPageIndexChanging method - which basically defeats the purpose here.
So, to summarize, can JavaScript access the OnPageIndexChanging method?
Thanks a lot
The OnPageIndexChanging event is a server-side event, so it's not surprising that your Javascript handler isn't getting triggered.
I'm not sure if ASP.Net has a "built in" way to do this; but you can do it by attaching your own Javascript listeners. Here is the general approach (I'm using JQuery to make it easier):
Write a JQuery selector that gets all the paging links that you want to confirm.
Add a click listener for each of those links
Make the confirm function the handler for those listeners
So, the code would look something like this:
$("#grid a").each(function () {
$(this).click(function () {
return confirm("really?");
});
});
Notes
Here grid is the ID of the GridView control, so #grid a selects every a tag within my grid.
Using return confirm() returns false if the user does not confirm, which effectively cancels the click event.

Show a loading animation while function completes

I have a function inside my .aspx.cs code which takes wuite a long time to do the processing until when I want to display a cool loading animation. I looked some of the earlier posts but either these didn't work for me, or were having solution specific to Page loading scenario (not loading a while a function completes).
I guess the right approach would be to fire a Javascript startLoader() function just before the the main function starts (which takes a long time), and then call a stopLoader() from the .aspx.cs itself to stop the loader when the function ends. Any suggestions how to implement this?
Yes, I've done this in ASP.NET Web From (not a ASP.NET MVC solution). You need to provide OnSubmit client side event handler. It basically break down to three parts: Javascript, HTML Div, and one line code behind:
Javscript:
function ShowLoading(e) {
// var divBg = document.createElement('div');
var divBg = document.getElementById('blockScreen');
var divLoad = document.createElement('div');
var img = document.createElement('img');
img.src = 'images/ajax-loader.gif';
divLoad.setAttribute("class", "blockScreenLoader");
divLoad.appendChild(img);
divBg.appendChild(divLoad);
document.getElementById('blockScreen').style.display = 'block';
// These 2 lines cancel form submission, so only use if needed.
//window.event.cancelBubble= true;
//e.stopPropagation();
}
function HideLoading() {
//alert('hideloading');
document.getElementById("form1").onsubmit = null;
document.getElementById('blockScreen').style.display = 'none';
//alert('done');
}
Add following DIV
<div id="blockScreen" class="blockScreen" style="display:none"> </div>
Finally, add the following to Page_Load in code behind.
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "submit", "ShowLoading()");
Now, all of your page postbacks are essentially have to call onsubmit event. It will display the animation before the page postback finishes.
if you really want to do, then the only way is webworkers. You've probably heard about them, or if not, i seriously recommend to have a look.
Yes, fire startLoader() on OnCliencClick of your button or whatever element you are using to fire the server-side event and call stopLoader() from the server-side at the end of your process. Something like this:
//rest of the server-side code above ...
Page.ClientScript.RegisterStartupScript(this.GetType(), "someKey", "stopLoader();", true);
If you don't mind that the browser is not responsive in the meantime, the simplest way of doing this is using an animated gif:
Activity indicators
ajaxload.info
webscriptlab
The trick is showing the image when starting your processing, and hiding it when finished. You can show it in an img, and use jQuery or whatever you want to show/hide it.
If you need the browser to keep responsive, use Web Workers. But be aware that some of the older browsers don't support it. See this reference

WebBrowser and javascript

I am working with a website that has javascript that does some changes on the page load. However, when I load the page and handle the DocumentCompleted event, this change isn't there. If I then continue paste the DocumentCompleted event, I can see the change happen. However I need this change to happen during DocumentCompleted so I can check some things.
Is there an other event I can subscribe to, or a way to cause the webBrowser to do all the javscript on page?
Edit: This is what I am talking about.
I loaded a sample page just to show you, and clicked the submit button with all fields empty to generate an the error.
Here is the result:
http://s8.postimage.org/zfv6stcar/sfsdfsdfds.jpg
Now if I take the HTML at that precise moment from that WebBrowser control, and render it somewhere else, those errors go away. The same thing happens when the server sends back those errors. If I handle the DocumentCompleted event and take the html, it isnt there. But after the event, it shows up in the control.
Hope you understand, it's hard to explain.
The problem seems to be that the DocumentCompleted event is being fired before the javascript. You should do some reading on how client side/server side things function.
One option is to make a separate method for the DocumentCompleted event and call it form the javascript after it has been completed. This would get the sequencing of these events working properly, but is not very ideal.
Alternatively, you could call the javascript code at the beginning of your DocumentCompleted event. The link below gives a pretty good explanation of how to go about that.
http://forums.asp.net/t/1117189.aspx/1
Personally, I would avoid using javascript and do the validation on the client side .NET, but I don't know enough about the website to really say.
EDIT:
This should be the script you are looking for. Alternatively here is a thread related to your issue. Sorry I don't have the exact code as I don't have a project to test this on.
http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
Calling JavaScript Function From CodeBehind
RE-EDIT:
What is happening on the link you provided in the comments, is that each textbox is calling some javascript as well as the submit button. The best way to examine this is using the "Inspect Element" in the right-click menu on Google Chrome. For example, doing this on the textbox would show that it is registered with a few events:
onfocus="$('f_tip_Username').style.display = 'inline'"
onblur="$('f_tip_Username').style.display = 'none'"
onchange="$('f_err_Username').style.display = 'none'"
The first the element with the ID 'f_tip_Username', sets the display style of that element to inline (visible).
The submit button calls the following:
onclick="return o_edit_profile_form.validate()"
Doing a find on "o_edit_profile_form" in the source code, you can find the exact javascript location that is being called. Enjoy!
FINAL EDIT (hopefully?):
Follow these steps: go to your site, right click and go view source. Do a find for "f_tip_Username". This is the ID of one of the div tags being used. The third entry of it, should be a "div tag" that is used under the first textbox to warn of "min 3 characters".
You'll notice above that in the code is a input type "text" with the Name "Username". Notice the three events it has registered in it:
onfocus="$('f_tip_Username').style.display = 'inline'"
onblur="$('f_tip_Username').style.display = 'none'"
onchange="$('f_err_Username').style.display = 'none'"
These either hide or make visible, the div tag we found (f_tip_username) and also a separate div tag (f_err_Username) which is the error message div tag. Let me know if you are not able to find these in the source. Follow the steps I provided and you will find it in the "view source" OR in the DocumentText.

YUI Button initiates Postback Twice

I'm using ASP.NET 2.0 under VS 2005.
Page_Load is getting called twice for my .aspx pages. AutoEventWireup is set to true, but even if I set it to false and manually add the EventHandler, it still gets fired twice.
// also set AutoEventWireup to false
public _Default() {
this.Load += new EventHander(this.Page_Load);
}
// oops -- fired twice
In the Default.aspx page, after the user enters their username & password, I do a redirect to another page, but it seems to redirect back to the Default.aspx page.
I don't have any <img> tags without a src. The tags that have a RunAt="server" attribute are <asp:PlaceHolder>.
For everything else, I use YUI CSS and JavaScript. I don't have any <ASP:> controls.
What am I missing?
Update
I'm using the Button widget from the YUI library. If you specify "submit" in both Javascript and in the HTML code for a button, then when you submit, that JavaScript event gets generated twice.
This was a pain to figure out: I started commenting out bits and pieces of JavaScript and CSS (especially the includes), until the event fired only once.
A redirect is a postback in ASP.NET. If you trigger an event(enter user name and click, 1 postback), redirect to the same page(2nd postback). Am I understanding you correctly?
Are you by any chance using this.PreviousPage in the redirected Page ?
So I'm using the YUI framework. And I'm using the Button widget. If you specify "submit" in both Javascript and in the HTML code for a button, then when you submit, that Javascript event gets generated twice. Just remove one of the submits.
This was a pain to figure out: just start commenting out bits and pieces of Javascript and CSS (especially the includes), until the event fires only once. That way you can see what is causing the Page_Load to get fired twice.

Categories