insert javascript only on page postback - c#

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>

Related

Execute jquery on first page visit

I have the following code on my Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "$('#sd').slideToggle(200);", true);
}
This is a jQuery call to toggle the visibility of a div with the id #sd.
This seems to work only when this.Page.IsPostBack == true?
I have a simple form on that page that works as expected.
The form contains an input field that gets processed and returns the result.
That works.
However, now i would like to add an option to access the page with the (input) parameter in GET, so processsing could be done on first visit.
What is wrong and why is it not working on first visit?
I found it.
Typically, after I posted a question on line:
I moved this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.flexibleArea.js"></script>
to after the title tag.
It seems like #sd wasn't being loaded at the time of the call.
Could anyone shed more light on this?

get update panel cause post back in pageLoad event

How I can determine what update panel cause postback in function pageLoad() event?
my pageLoad evenet fires twice and I think it happend bacause of my 2 update panels
thanks
You should be able to tell this from the __EVENTTARGET form field.
You could handle the BeginRequest-Event instead and use the get_updatePanelsToUpdate() method to get the ID(s) of the UpdatePanel(s) that should re-render their content:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(onBeginRequest);
function onBeginRequest(sender, args) {
var updatePanelID = args.get_updatePanelsToUpdate();
}
</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();

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

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)
{
}

Categories