Javascript event on page postback - c#

Is there any javascript event which is triggered on postback?
If not, how can I run client side code immediately after or before a page postback?

I believe what you are looking for is the Sys.WebForms.PageRequestManager beginRequest Event
Excerpt:
The beginRequest event is raised before the processing of an
asynchronous postback starts and the postback is sent to the server.
You can use this event to call custom script to set a request header
or to start an animation that notifies the user that the postback is
being processed.
Code Sample: (From the link)
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args)
{
var elem = args.get_postBackElement();
ActivateAlertDiv('visible', 'AlertDiv', elem.value + ' processing...');
}
function EndRequestHandler(sender, args)
{
ActivateAlertDiv('hidden', 'AlertDiv', '');
}
function ActivateAlertDiv(visstring, elem, msg)
{
var adiv = $get(elem);
adiv.style.visibility = visstring;
adiv.innerHTML = msg;
}
</script>
I hope that helps. The PageRequestManager class seems to be little known about and little utilized.

Take a look at:
Run javascript function after Postback
I solved my problem using this:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
alert('Postback!');
});
</script>
there are a lot of options too, like
$('#id').live('change', function (){});
$(document).ready(function () {});
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
and keep going. depends on what you need.
PageRequestManager events: https://learn.microsoft.com/en-us/previous-versions/aspnet/bb398976(v=vs.100)

You could add the javascript in your page load like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('hello world');", true);
OR
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertScript",
"function Hello() { alert('hello world'); }", true);

The Page.ClientScript object has a RegisterOnSubmitStatement This fires after any input submits the form. This may or may not be what you're looking for, but I've used it for notifying the user of unsaved changes in editable forms.
The advantage to using this over RegisterStartupScript is that with RegisterOnSubmitStatement, if a user navigates away and back using the browser, whatever script you've injected using RegisterStartupScript could possibly fire again, whereas RegisterOnSubmitStatement will only run if the user has submitted the form.

Use AJAX, with an event handler for the onComplete.

The onsubmit event on the form tag
When using jQuery it's like this
$("#yourformtagid").submit(function () {
...
}

There isn't a javascript event triggered when a page loads after a postback, but you can add javascript to your html template (.aspx file) and only run it if the page was posted, like this:
<script type='text/javascript'>
var isPostBack = '<%= this.IsPostBack%>' == 'True';
if (isPostBack) {
alert('It's a PostBack!');
}
</script>
If you want to customize the javascript to run only under particular conditions (not just any postback), you can create a page-level variable (protected or public) in your page's class and do something similar:
var userClickedSubmit = '<%= this.UserClickedSubmit%>' == 'True';
if (userClickedSubmit) {
// Do something in javascript
}
(Nothing against ClientScript.RegisterStartupScript, which is fine - sometimes you want to keep your javascript in the page template, sometimes you want to keep it in your page class.)

Related

Delaying Calling JQuery or javascript method from c#

I've got a mixture of JQuery and Ajax partial postbacks on a webforms page and I'm trying to stop the user navigating away from a page without their changes having been saved.
It's working pretty well unless one of the data validators on the page is invalid. There is a jquery method on the submit button that basically nulls the onbeforeunload event. In the event that the validators are invalid, I dont want that to happen, so I turned off the client side validation, and in the method, called Page.Validate(), then if the page was invalid, I tried to register a startup script as described here to reset like so:
if (!Page.IsValid) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "setConfirmUnload(true);", true);
return;
}
If I run the click submit and the page is invalid, the call to setConfirmUnload(true) happens, but the method cant be found (presumably because I re-set this up every time a postback happens?
The actual error is " JavaScript runtime error: 'setConfirmUnload' is undefined", possibly because the bindEvents() hasnt yet re-run and therefore created it?
I thnk my problem stems from the fact that I am using partial postbacks and autopostbacks, setting up data as the user modifies the form. By default that blitzes my jquery, so I rebind the jquery calls on document.ready() as well as on postback using
<script type="text/javascript">
// attach the event binding function to every partial update
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (evt, args) {
bindEvents();
});
</script>
And my Bind Events method looks like:
function bindEvents() {
// stuff removed for brevity here...
$(function () {
// Prevent accidental navigation away
$(':input, select').bind(
'change', function () { setConfirmUnload(true); });
$('.noprompt-required').click(
function () { setConfirmUnload(false); });
function setConfirmUnload(on) {
window.onbeforeunload = on ? unloadMessage : null;
}
function unloadMessage() {
return ('You have entered new data on this page. ' +
'If you navigate away from this page without ' +
'first saving your data, the changes will be lost.');
}
window.onerror = UnspecifiedErrorHandler;
function UnspecifiedErrorHandler() {
return true;
}
});
}
If that's the case, is there a way I can force the script to run after the bindEvents() call has happened?

page life cycle when OnServerValidate fails (custom validator)

I have a gridview within an update panel. When the page loads I have javascript enable/disable fields in the gridview (call it Function X(). When the update panel updates I use Sys.Application.add_load() to reload Function X(). This is all fine and dandy.
My problem:
When the custom validator's onservervalidate fails (args.IsValid = false) Function X() is not called and it needs to be called to enable/disable fields. How do I call Function X() at this point in the life cycle?
You will have to manually re-call your JavaScript functions, and you can do so like this, using JavaScript:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequest);
function EndRequest(sender, args) {
functionX();
}

Call Javascript from code behind after partial postback

I have a RadTreeView in a UserControl that is in an UpdatePanel and opens in a jQuery popup window. A button within the control raises a click event that is picked up by the containing page and results in the user control adding a new node to the RadTreeView from the code behind of the user control. Once this happens I want to then call a JavaScript function (that loops through all nodes and sets their visibility based on a filter string). Ideally I want to set this script call from the same function within the user control.
I have tried the following from code behind of the user control
ScriptManager.RegisterClientScriptBlock(
this,
this.GetType(),
"filter",
"filterItems('" + this.RadTV.ClientID + "','" + this.txtFilter.Text + "');",
true );
I have also tried something similar from the code behind of the parent page and registered the Script Block with the appropriate UpdatePanel.
In both cases, the Script is never called.
Any ideas?
Cheers
Stewart
You need handler for doing this.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandle);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);
function beginRequestHandle(sender, Args) {
//Do something when call begins.
}
function endRequestHandle(sender, Args) {
Yourfunction();//Call your function here
}
</script>

asp.net accessing javascript variables after ajax updatepanel

I'm using AJAX on an ASP.NET web project to update a page. Some of my functions return XML that I want to embed on the page after it reloads. This part works, here's a sample of how it looks at the top of the page:
var productXML = "<?xml version=\"1.0\"?><ArrayOfProduct xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Product><ActualProdID>123</ActualProdID><Name>Test</Name><Description>Test</Description><Edition>Test</Edition><Platform>Test</Platform><Family>Test</Family><Type>Test</Type><DeploymentTypes>Test</DeploymentTypes><BaseActualProdID>Test</BaseActualProdID><Price>0</Price></Product></ArrayOfProduct>";
Later in the page I'm trying to use the XML but it's not working. I tried to do something simple and just throw an alert box in that looks like this:
<script type="text/javascript">
function closeLoading()
{
jQuery('.pleaseWaitPanel').css({ 'display': 'none', 'visibility': 'hidden' });
alert("here");
alert(productXML);
alert("here2");
}
</script>
closeLoading() is called inside:
window.onload = function () { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading); };
It loads the jQuery and the first alert "here" works perfect. When I go to alert the productXML, nothing happens. It doesn't throw a JavaScript error, I'm using Firebug. I can confirm the XML is on the page.
Any help on this would be GREATLY appreciated!!
From your code snippets, it looks like your closeLoading function is only being called in your window.onload function. This means that it won't be called after any Ajax request completes as the window won't be reloaded.
I would try moving your call to Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading) to just before your closing server-side form tag:
<form runat="server">
...
<script>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
</script>
</form>
Hope this helps.
var productXML
Is a ServerSide variable, so you don't have access to this in Client script.
If you want to use in a javascript function you can do this :
1) Put the result in a textbox hidden, like
<input type='hidden' value='<%=productXML%>'>
then simply get the value of the textbox.

jquery with update panel

i have a problem while using jquery context menu and update panels. i am writing the javascript of the context menu in the RenderBeginTag of a Customtextbox control using htmlTextWriter. everything works fine, i can right click on every textbox and the menu appears.
but when i triger a partial postback using an asp.net updatepanel, the menu won't be displayed. it seems that the binding between jquery and the html is lost when partial post back happened.
is there any better way to place dynamic javascript code other than in RenderBeginTag ? how can i solve this issue?
You're right, the updatepanel will remove your javascript bindings.
In your updatepanel postback, re-register the javascript in question.
Something like:
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(typeof(Page), "ReApplyJavascript", "<script type=text/JavaScript>YourJavascriptInitMethod();</script>", false);
If that doesn't work. You may need to use:
ScriptManager.RegisterStartupScript(Page, typeof(Page), "ReApplyJavascript", "<script type=text/JavaScript>YourJavascriptInitMethod();</script>", false);
You need to reinitialize the menou after UpdatePanel Update.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// Here initialize the menou
}
</script>

Categories

Resources