How to intercept any postback in a page? - ASP.NET - c#

I want to intercept any postbacks in the current page BEFORE it occurs . I want to do some custom manipulation before a postback is served. Any ideas how to do that?

There's a couple of things you can do to intercept a postback on the client.
The __doPostBack function looks like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
Notice that it calls "theForm.onsubmit()" before actually doing the postback. This means that if you assign your form an onsubmit javascript function, it will always be called before every postback.
<form id="form1" runat="server" onsubmit="return myFunction()">
Alternately, you can actually override the __doPostBack function and replace it with your own. This is an old trick that was used back in ASP.Net 1.0 days.
var __original= __doPostBack;
__doPostBack = myFunction();
This replaces the __doPostBack function with your own, and you can call the original from your new one.

Use the following options
All options works with
ajax-enabled-forms and simple forms.
return false to cancel submit within
any submit-handler.
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "submit-handler", "alert(\"On PostBack\");");
Equivalent javascript --don't use this code with previous code simultaneously
// Modify your form tag like this
<form onsubmit="javascript:return submit_handler();" ...>
// Add this script tag within head tag
<script type="text/javascript">
function submit_handler() {
// your javascript codes
// return false to cancel
return true; // it's really important to return true if you don't want to cancel
}
</script>
And if you want complete control over __doPostBack put this script next to your form tag
<script type="text/javascript">
var default__doPostBack;
default__doPostBack = __doPostBack;
__doPostBack = function (eventTarget, eventArgument) {
// your javascript codes
alert('Bye __doPostBack');
default__doPostBack.call(this, eventTarget, eventArgument);
}
</script>
Tested with ASP.NET 4.0

To get the postback before a page does, you can create an HttpHandler and implement the ProcessRequest function.
Check this Scott Hanselman link for a good blog post on how to do it (including sample code).

Page.IsPostBack is your friend.

You can check for a postback in one of the page events for your form.
If you want to take some action on postback that involves creating controls or manipulating viewstate then you may want to come in on an earlier event like Page_Init.
Try this:
protected void Page_Init(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//Check for your conditions here,
if (Page.IsAsync)
{
//also you may want to handle Async callbacks too:
}
}
}

not sure, but I think you are looking for..
if (Page.IsPostBack)
{
}

Related

ASP.Net Ajax UpdatePanel to be loaded only after the page is ready

I am using ASP.Net AJAX UpdatePanel to load the right part of the page.
As that part will take some time to load, I would like to load it after the other parts of the page is loaded.
I can use either normal AJAX or ASP.Net AJAX but I chose to use the latter as I want to try it out.
I found out that my UpdatePanel is always loaded.
I want it to be loaded only after the page is ready.
Some says to use the timer, some says to use some javascript.
But I still can't get it done.
So, these are my 2 obstacles, to stop loading when the page starts and to start loading when the page is ready
why don't you enable and disable on page events? for example. try in Page_PreLoad event, set the update panel's enable property to False. While in Page_LoadComplete event, set it back to enabled = true
UpdatePanels use Ajax to update, not on first load.
If you want it to load quickly on first load, avoid any expensive processing, database calls on load. Put them in an
if(IsPostBack)
{
//your long processing
}
Now use an AsyncPostBackTrigger to make your updatePanel postback.
try with this code ( Conditional Mode + Update Method)
<asp:UpdatePanel ID="YourIdPanel" UpdateMode="Conditional" runat="server">
//In order to force loading
YourIdPanel.Update();
<script type="text/javascript">
var currentItemID=$('#<%= labcurrentItemID.ClientID %>').html();
if (currentItemID != null) {
$(document).ready(function () {
$('#main_container').load('/Custom/Going%20Places/PopularRelatedArticle.aspx?currentID=' + currentItemID);
});
}
else {
$(document).ready(function () {
$('#main_container').load('/Custom/Going%20Places/PopularRelatedArticle.aspx?currentID={7F0811A7-D484-4675-8A23-0AEB235B9B5F}');
});
}
</script>

Document.Ready() is not working after PostBack

I have a page that contains a user control within an update panel. $(document).ready(function() ) { is called and executes the code correctly when the page firsts loads but if the user clicks a button (within the user control), the document.ready() doesn't get called (document.load, onload also don't work)
I have researched this on the net and found similar problems but nothing that can explain why this isn't working. What other causes can there be for document.ready not working?
This will be a problem with partial postback. The DOM isn't reloaded and so the document ready function won't be hit again. You need to assign a partial postback handler in JavaScript like so...
function doSomething() {
//whatever you want to do on partial postback
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(doSomething);
The above call to add_endRequest should be placed in the JavaScript which is executed when the page first loads.
Instead of $(document).ready you could use function pageLoad(){}.
It's automatically called by the ScriptManager on a page, even on a postback.
I've run into this a while ago, as El Ronnoco said, it has to go with the DOM not being reloaded. However you can simply change
$(document).ready(function() {
to
Sys.Application.add_load(function() {
This will force it to run on every postback.
You can use function pageLoad() as well, but you can only have one pageLoad function, whereas with Sys.Application.add_load, you can add as many handlers as you wish.
Bestest way is
<asp:UpdatePanel...
<ContentTemplate
<script type="text/javascript">
Sys.Application.add_load(LoadScript);
</script>
you hemla code gose here
</ContentTemplate>
</asp:UpdatePanel>
Javascript function
<script type="text/javascript">
function LoadScript() {
$(document).ready(function() {
//you code gose here
});
}
</script>
or
Its under UpdatePanel than you need to register client script again using
ScriptManager.RegisterClientScript
or
$(document).ready(function() {
// bind your jQuery events here initially
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// re-bind your jQuery events here
loadscript();
});
$(document).ready(loadscript);
function loadscript()
{
//yourcode
}
This is an example that worked for me in the past:
<script>
function MyFunction(){
$("#id").text("TESTING");
}
//Calling MyFunction when document is ready (Page loaded first time)
$(document).ready(MyFunction);
//Calling MyFunction when the page is doing postback (asp.net)
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(MyFunction);
</script>
This code below works nice to solve this problem. As indicated in link posted before (http://encosia.com/document-ready-and-pageload-are-not-the-same/), when you have an asp.NET with updatePanels you shall use function pageLoad(). When you have only one page and in each postback it will be fully reloaded, the $(document).ready() is the right option.
Example using pageLoad:
function pageLoad() {
$(".alteraSoVirgula").keyup(function () {
code here
})
}
I was also facing the same problem but i found the jQuery $(document).ready event handler works when page loads, but after ASP.Net AJAX UpdatePanel Partial PostBack it does not get called. so use Sys.Application.add_load(function(){}); instead of $(document).ready.
This works perfectly for me :)
<script>
Sys.Application.add_load(function() {
//Your code
});
</script>
$(document).ready(function () {
PreRoles();
});
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
PreRoles();
}
});
};
function PreRoles() {
// Add codes that should be called on postback
}
Most of the times, this is happening because of the Updatepanle.
Just put postback triggers to the button and it will solve this.

How to load javascript function from an dynamicall added control?

The Master page got a ScriptManager.
Then i got a Control with a ScriptManagerProxy and an UpdatePanel.
Inside the UpdatePanel there I dynamically add a Control (also containing a ScriptManagerProxy) and from that control I need to run some JavaScript code.
DynamicControl.ascx:
<script type="text/javascript">
function doSomething() {
alert(1);
}
</script>
DynamicControl.ascx.cs:
public void Page_Load(object sender, EventArgs e)
{
...
ScriptManager.RegisterStartupScript(
this.Page, this.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
My problem is that the function "doSomething()" is never called and i dont know why. :S
Edit: It is called but not directly when i add the control.
If I do code like this, there will be an alertwindow:
"<script type='text/javascript'>alert(1);</script>"
Ok I think i need to add some more information:
The control is dynamical added inside a jQuery Dialog. And I found out that the javacode is first executed after i close and then open the dialog. Some kind of event is triggered so that the code is executed there i think. Is it possible to force this event? so the scripts are executet directly when the control is added ?
placeHolder.Controls.Add(dynamicReportControl);
This c# code doesn't execute the javascript tag immediately ?
Please try something like this
ScriptManager.RegisterStartupScript(
this.UpdatePanel1, this.UpdatePanel1.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
Where UpdatePanel1 is your UpdatePanel
Try setting the addScriptTags argument to true, and remove the script declaration from your code.
Is that code only supposed to run on every request? If so, why not just add this code to the ASCX:
window.onload = doSomething();

insert javascript only on page postback

I'm sure this is fairly straightforward but i'm having trouble getting it to work. I want to add a javascript function to my page, but only when the page postsback.
So I have a button that calls some server-side code, and when it is finished and the page is re-loading I want the javascript function to be called.
Thinking about this i guess I could just add a hidden variable and set it when the button is clicked, but i think i'd rather just insert the javascript onto the page when it is loading back.
Is this possible, or even a good way to do it?
Thanks,
Neil
Edit: Okay this is my OnClick method in the C# code.
protected void Save(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "<script type=\"text/javascript\">alert('hello world');</script>");
EnforcementMatch(false);
EnforcementMatch(true);
ApplicationNotMatch();
ApplicationMatch();
Response.Redirect(Request.Url.ToString());
}
Another Edit: Just realised that the response.redirect at the bottom reloads my page cancelling out the code I put in, duh!
You can use ClientScriptManager.RegisterClientScriptBlock
http://msdn.microsoft.com/en-us/library/btf44dc9.aspx
If you place it on the button click event, you don't have to worry if it's a postback or not.
You know about the IsPostBack function, right?
IsPostBack (MSDN)
if (IsPostBack)
{
ClientScript.RegisterClientScriptBlock()
}
This script will be fired with every single postback from updatepanel
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
alert('hello world');
});
</script>
Place it in a separate script block, only to be rendered on postback.
<script type="text/javascript" runat="server" visible="<%#this.IsPostBack %>">
TheCode();
</script>

Executing a Javascript function from an asp.net codebehind?

OK, this feels like a question that should be easy to answer, but as with so much mixing of asp.net and jQuery, it's a bit of a nightmare.
What I want to do is be fading a div in and out at various times during the client's viewing of my asp.net page; I fade it out using jQuery's fadeTo() before triggering an UpdatePanel update (to indicate that the data there is not fresh) and I want to fade it in again once the UpdatePanel has been updated. I've gotten as far as updating the UpdatePanel in the codebehind, and this results in the div's content changing... but how do I fade the div back in again?
The way I see it, there are 2 ways; register an event handler on page load to detect when the div's content has been changed and fade it back in, or call a function from the asp.net codebehind when I've updated the div to fade it back in.
In the first case, there doesn't seem to be any event triggered by the div's content changing, so I can't seem to do that. If anyone knows how I could get a client event to trigger when I update the div, that would be a nice solution.
In the second case, I thought that this was what ClientScriptManager was for, but it doesn't quite do what I want. I want to be able to register a particular Javascript function with ClientScriptManager and then tell ClientScriptManager to execute it in the client, from my codebehind. You can't seem to do that. ClientScriptManager.RegisterClientScriptBlock() simply inserts some <script> into the HTML output, rather than calling a function. Presumably this would work if I kept registering things like:
<script>fadeBackIn();</script>
because the Javascript would be immediately evaluated and run, but this feels messy, and that feeling is intensified by the fact that I'd have to keep randomly generating a new unique value for the key argument of ClientScriptManager.RegisterClientScriptBlock(), because it's specifically designed to stop this kind of repeated code. However, I'm struggling to see an alternative. Can anyone come up with a good idea as to a better mechanism to get this to work?
I'd really like something along the lines of:
ClientScriptManager.RegisterClientScriptFunction("fadeBackIn", "function fadeBackIn(){ ... }");
[...]
ClientScriptManager.ExecuteClientScriptFunction("fadeBackIn");
but I don't see that functionality available. :-(
You can attach to the page loaded event. The pageLoaded handler recieves an argument of type PageLoadedEventArgs which contains a get_panelsUpdated method that you can call to enumerate all the UpdatePanels whose content was just updated.
Example:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded(sender, args)
{
var panels = args.get_panelsUpdated();
if (panels.length > 0)
{
for (var i in panels)
{
if (panels[i].id == "DesiredUpdatePanelId")
{
fadeBackIn();
}
}
}
}
Because html is stateless, you'll need an asynchronous way of determining if the content has changed in your div. I would try using the window.setInterval to check if your content has changed every 500ms or so.
If your div looks like this:
<div id="mycontent">Blah, blah.</div>
Then this might be a solution:
$(function(){
var $mycontent = $('#mycontent');
var myContentHtml = $mycontent.html();
var intervalId;
function checkIfDivChanged()
{
window.clearInterval(intervalId);
if (myContentHtml != $mycontent.html())
{
myContentHtml = $mycontent.html();
// run update here..
fadeBackIn();
// if you want to stop the check then uncomment next line..
// return;
}
intervalId = window.setInterval(checkIfDivChanged, 500);
}
checkIfDivChanged();
});
If you are using, or are willing to use the ASP.NET Ajax Control Toolkit, it contains a control that does exactly what you are looking for: UpdatePanelAnimation.
Take a look here for more information on that control, and here for more information on using animations.
I have written small script with pure JavaScript (no jQuery required), you can just have this script in your page and change the alert part.. plus of course the ID of the div element.
<script type="text/javascript">
var _watchTimer = 0;
window.onload = function WindowLoad(evt) {
_watchTimer = window.setInterval("WatchForChange();", 100);
}
function WatchForChange()
{
var oDiv = document.getElementById("MyDivToWatch");
if (oDiv == null)
{
window.clearInterval(_watchTimer);
return;
}
var prevHtml = oDiv.getAttribute("prev_html") || "";
var curHtml = oDiv.innerHTML;
if (prevHtml != curHtml)
{
if (prevHtml.length > 0)
{
alert("content changed");
}
else
{
//first run, ignore
}
oDiv.setAttribute("prev_html", curHtml);
}
}
</script>
<div id="MyDivToWatch">I can be changed..</div>
<button type="button" onclick="document.getElementById('MyDivToWatch').innerHTML += ' like this..';">Change</button>
Added the whole code used to test, used a button to dynamically change the contents but it should work with changing it via AJAX call aka UpdatePanel.

Categories