Is there a global "onRequestComplete" event when using ASP.Net Update Panels? - asp.net

I have a master page with a public ShowWaitingDialog property. When set to true, I simply show a modal "Please wait..." overlay when the form is submitted. This is done by registering a client-side function called ShowWaitingDialog() using the following:
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ShowWaitingDialog", "ShowWaitingDialog()");
As a side note, I also have a function the coder can use if linking to a page that may take a while to load:
public void AttachWaitingDialog(HyperLink HyperLinkControl){
if (this.ShowWaitingDialog)
HyperLinkControl.Attributes.Add("onclick", "ShowWaitingDialog();");}
These work just fine until an UpdatePanel is introduced onto the page. The dialog is correctly shown when a postback happens inside an update panel. However, it never goes away when the request is complete. I was hoping there was some sort of global complete event that the Microsoft ajax framework uses when making update panels requests. That way I could close my modal overflow when executed. Is there?
I haven't tried it yet, but I guess I could use the ScriptManager to always register a startup script which hides the modal overlay, but I was wondering if there was another way.

You can use Javascript and use the PageRequestManager clientside api provided by Microsoft Ajax framework.
<script type='text/javascript'>
var pageMgr = Sys.WebForms.PageRequestManager.getInstance();
pageMgr.add_beginRequest(BeforeAjaxRequest);
pageMgr.add_endRequest(AfterAjaxRequest);
function BeforeAjaxRequest(sender, args)
{
alert('MyReqeustStart');
}
function AfterAjaxRequest(sender, args)
{
alert('MyReqeustEnd');
}
</script>
More Details here:
http://msdn.microsoft.com/en-us/library/bb311028.aspx

I'm not sure with UpdatePanels, but you might take a look at the Application_EndRequest method in Global.asax

Related

Register JavaScript alert at extreme end using RegisterStartupScript

(Note: Just to clarify the problem is not specifically related to C1WebDateEdit. It could be with any custom control which require JavaScript to render actual control)
I have many C1WebDateEdit controls in my page. On a button click based on some condition I am displaying JavaScript alert message ScriptManager.RegisterStartupScript. These controls are inside UpdatePanel. The issue I am facing with it is, when these C1WebDateEdit has not value and page displays alert message, it displays "01/01/0001" behind the alert box and on closing alert it shows empty textboxes.
The reason is, C1WebDateEdit creates actual control using JavaScript. and page renders alert message JavaScript before C1WebDateEdit controls' JavaScript.
For example:
HTML markup
alert JavaScript
C1WebDateEdit JavaScript
Logical solution is get alert JavaScript after C1WebDateEdit JavaScript because it will allow C1WebDateEdit to load fully before alert box.
I found no inbuilt way in asp.net to change sequence, so I tries solution given here but It didn't work for me.
One possible solution I am thinking that I create Custom or WebUserControl and place at it last at the page in the UpdatePanel and PreRender event I call ScriptManager.RegisterStartupScript to register alert message. Logically I think it will work but trying to find that any one implemented any other solution for it?.
Other possible solution is use "pageLoaded" event of PageRequestManager. I created below function for temporary fix:
function delayedAlertBox(strMsg)
{
var fnc = function (a, b)
{
//remove reference so on next call it do not show previous alerts.
Sys.WebForms.PageRequestManager.getInstance().remove_pageLoaded(fnc);
alert(strMsg);
}
//add function reference to call on Ajax pageloaded event
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(fnc);
}
and calling in asp.net like simple function as given below:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "dd", "delayedAlertBox('Hi, how are you?')", True)
But still looking for any other good alternative. If I found other, I will post it.

Why javascript function not working from content page onload?

I am using ASP.NET 3.5.
I have a content page and I want to call a javascript function on this page's load event.
I tried adding:
onload="GetLocalDate();"
within the content page placeholder tag, but it is not working. But when I call this function from any button's OnClientClick event, it works.
How to make it work on Content Page's load event?
The content page "Placeholder" tag is a server side only control. It doesn't produce any code on the client other than arranging its contents etc. As such, the JavaScript onload handle is never rendered.
Examine your browser / client-side source to verify this.
Have you tried calling from document.ready?
$(document).ready(function () {
GetLocalDate();
}
Put that inside script tag on your page
<script type="text/javascript">
function pageLoad(){
GetLocalDate();
}
</script>
$(document).ready(function () {
GetLocalDate();
}
Should work. Since it was not working for you, I would assume that you do not have a reference to the jQuery library in your page.
If you don't want to include the jQuery library in your project for some reason, you could inject it from server-side code within your content page:
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(...) <-- add necessary details here (the Type, scriptname, the text, and a Boolean to whether you need it to include its own tags)
You should also check to make sure it hasn't already been registered before using it though (IsStartupScriptRegistered).

__doPostBack outside of href causes full page postback

I have a custom control (ascx) which implements the IPostBackEventHandler interface for intercepting custom events triggered by custom rendered HTML links.
In this control I use an update panel and inside the update panel I use a literal control in which I render custom HTML links.
When I render the HTML links inside the literal control I use a StringBuilder with the following code:
sb.AppendFormat ("Text",
this.Page.ClientScript.GetPostBackClientHyperlink(this, custom_string_param));
Hyperlinks are rendered fine, and when clicking on them an asynchronous postback is triggered and a partial update is fired (since all links are rendered inside the Update panel).
The problem is that I need to do some custom Javascript before firing the __doPostBack which is rendered with the above code. So here is a simplified version of the changed code:
sb.AppendFormat ("Text",
custom_string_param);
Also in the ascx markup I use the following code (inside or outside the Update panel):
<script language="javascript" type="text/javascript">
function JSFunc(param) {
// custom js code here ....
__doPostBack('<%=this.ClientID%>', param);
}
</script>
The problem here is that when a link is clicked it performs a full postback and not a partial one. I also tested more simple versions of the above code and it seems that if you remove the __doPostBack from the href or the onclick events from the link ( tag) and move it to a custom js function which in turns you supply to the link, a full postback is triggered.
Note that there is no error on the page and in both cases the code work correctly. The page is rendering correctly depending on the parameters returned from the __doPostBack, but in the second case a full instead of partial postback is firing.
Any ideas?
Thanks in advance,
George
I think you can't call __doPostBack with the ClientID. It actually uses UniqueIDWithDollars, but generally with ASP.NET Web Forms I say: you don't want to know.
Since calling this method is all about abstracting away the details of how post back works, you would be better off asking the framework for the code. Luckily, there's a special method just for that, which will take care of the details. In your code it would look like something like this:
<script language="javascript" type="text/javascript">
function JSFunc(param) {
// custom js code here ....
<%= Page.ClientScript.GetPostBackEventReference(this, custom_string_param) %>
}
</script>
This let's the client script manager create the piece of JavaScript code, using a reference to your user control (this) and any custom event argument (custom_string_param).
There's one caveat though. When calling it this way, it will add javascript: to the beginning of the string.
To override this behaviour, you need to use an overload of GetPostBackEventReference that accepts an instance of PostBackOptions as its first argument, the instance having its RequiresJavaScriptProtocol property set to false.
PostBackOptions options = new PostBackOptions(this, custom_string_param)
options.RequiresJavaScriptProtocol = false;
Page.ClientScript.GetPostBackEventReference(options)

ASP.net Ajax Navigateaway JQuery issue

I am using the below mentioned jQuery scripts to alert users when they try to navigate before saving data.
NavigateAway
The problem I am having is the validation doesn't work for the buttons that are in updatePanel.
All the others work well.
Thanks in advance
Based on the code you linked to, the way this plugin works is by subscribing to the onbeforeunload event. I don't believe this event is triggered when UpdatePanel executes async requests.
Take a look at the example here of how to manually trigger the validation: calling onbeforeunload from an updatepanel (note, code copied from the link provided).
function pageLoad() {
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
}
// This fires before the partial postback occurs
function InitializeRequest(sender, args) {
// Call the validation function here, should be something like this
handleOnBeforeUnload();
}

SimpleModal breaks ASP.Net Postbacks

I'm using jQuery and SimpleModal in an ASP.Net project to make some nice dialogs for a web app. Unfortunately, any buttons in a modal dialog can no longer execute their postbacks, which is not really acceptable.
There is one source I've found with a workaround, but for the life of me I can't get it to work, mostly because I am not fully understanding all of the necessary steps.
I also have a workaround, which is to replace the postbacks, but it's ugly and probably not the most reliable. I would really like to make the postbacks work again. Any ideas?
UPDATE: I should clarify, the postbacks are not working because the Javascript used to execute the post backs has broken in some way, so nothing happens at all when the button is clicked.
Both of you were on the right track. What I realized is that SimpleModal appends the dialog to the body, which is outside ASP.Net's <form>, which breaks the functionality, since it can't find the elements.
To fix it, I just modified the SimpleModal source to append eveything to 'form' instead of 'body'. When I create the dialog, I also use the persist: true option, to make sure the buttons stay through opening and closing.
Thanks everyone for the suggestions!
UPDATE: Version 1.3 adds an appendTo option in the configuration for specifying which element the modal dialog should be appended to. Here are the docs.
All standard ASP.NET postbacks work by calling a __doPostBack javascript method on the page. That function submits the form (ASP.NET only really likes one form per page) which includes some hidden input field in which all the viewstate and other goodness lives.
On the face of it I can't see anything in SimpalModal that would screw up your page's form or any of the standard hidden inputs, unless the contents of that modal happened to come from a HTTP GET to an ASP.NET page. That would result in two ASP.NET forms being rendered into one DOM and would would almost certainly screw up the __doPostBack function.
Have you considered using the ASP.NET AJAX ModalPopup control?
Web browsers will not POST any disabled or hidden form elements.
So what's happening is:
The user clicks on a button in your dialog.
The button calls SimpleModal's close() method, hiding the dialog and the button
The client POSTs the form (without the button's ID)
The ASP.NET framework can't figure out which button was clicked
Your server-side code doesn't get executed.
The solution is to do whatever you need to do on the client (closing the dialog in this case) and then call __doPostback() yourself.
For example (where "dlg" is the client-side SimpleModal dialog reference):
btn.OnClientClick = string.Format("{0}; dlg.close();",
ClientScript.GetPostBackEventReference(btn, null));
That should hide the dialog, submit the form, and call whatever server-side event you have for that button.
#Dan
All standard ASP.NET postbacks work by calling a __doPostBack javascript method on the page.
asp:Buttons do not call __doPostback() because HTML input controls already submit the form.
got caught out by this one - many thanks to tghw and all the other contributors on the appendto form instead of body fix. (resolved by attributes on the 1.3 version)
btw: If anyone needs to close the dialog programmatically from .net - you can use this type of syntax
private void CloseDialog()
{
string script = string.Format(#"closeDialog()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
}
where the javascript of closedialog is like this....
function closeDialog() {
$.modal.close();
}
I have found the following works without modifying simplemodal.js:
function modalShow(dialog) {
// if the user clicks "Save" in dialog
dialog.data.find('#ButtonSave').click(function(ev) {
ev.preventDefault();
//Perfom validation
// close the dialog
$.modal.close();
//Fire the click event of the hidden button to cause a postback
dialog.data.find('#ButtonSaveTask').click();
});
dialog.data.find("#ButtonCancel").click(function(ev) {
ev.preventDefault();
$.modal.close();
});
}
So instead of using the buttons in the dialog to cause the postback you prevent their submit and then find a hidden button in the form and call its click event.
FWIW, I've updated the blog post you pointed to with come clarification, reposted here - the reasoning & other details are in the blog post:
The solution (as of my last checkin before lunch):
Override the dialog's onClose event, and do the following:
Call the dialog's default Close function
Set the dialog div's innerHTML to a single
Hijack __doPostBack, pointing it to a new function, newDoPostBack
From some comments I’ve seen on the web, point 1 needs some clarification.  Unfortunately, I’m no longer with the same employer, and don’t have access to the code I used, but I’ll do what I can.  First off, you need to override the dialog’s onClose function by defining a new function, and pointing your dialog to it, like this:
$('#myJQselector').modal({onClose: mynewClose});
Call the dialog's default Close function.  In the function you define, you should first call the default functionality (a best practice for just about anything you override usually):
Set the dialog div's innerHTML to a single – This is not a required step, so skip it if you don’t understand this.
Hijack __doPostBack, pointing it to a new function, newDoPostBack
function myNewClose (dialog)
{
dialog.close();
__doPostBack = newDoPostBack;
}
Write the newDoPostBack function:
function newDoPostBack(eventTarget, eventArgument)
{
var theForm = document.forms[0];
if (!theForm)
{
theForm = document.aspnetForm;
}
 
if (!theForm.onsubmit || (theForm.onsubmit() != false))
{
document.getElementById("__EVENTTARGET").value = eventTarget;
document.getElementById("__EVENTARGUMENT").value = eventArgument;
theForm.submit();
}
}
The new Jquery.simplemodal-1.3.js has an option called appendTo. So add an option called appendTo:'form' because the default is appendTo:'body' which doesn't work in asp.net.
Had the same problem, but {appendTo:'form'} caused the modal popup to be rendered completely wrong (as though I had a CSS issue).
Turns out the template I'm building on top of has includes that put other forms on the page. Once I set {appendTo:'#aspnetForm'} (the default Asp.net form ID), everything worked great (including the postback).
In addition to tghw's answer, this excellent blog post helped me: jQuery: Fix your postbacks in Modal forms -- specifically BtnMike's comment: "You also must not have CssClass=”simplemodal-close” set on your asp:button." Taking that off the class was the not-obvious-to-me solution.
-John
if you don want modify the SimpleModal source.
try this..
After you call the modal() method add this:
$("#simplemodal-overlay").appendTo('form');
$("#simplemodal-container").appendTo('form');
the SimpleModal plugin add two this to your markup.
'simplemodal-overlay' for the background
'simplemodal-container' containig the div that you whant as pop up modal.

Resources