Javascript: Referring to control before page is loaded - asp.net

I have a composite control on an ASPX page. There is Javascript on the ASPX page that gets loaded before the control. Now, since the script refers to the control element which does not exist when the script is loaded, this is throwing a Javascript error of "Obect not defined". Attaching the script to the onload event of the control gives "Sys not defined".
Any Idea?
The script is in an external file.

You need to either move the Javascript function below the control creation, or add it inside a window.load event handler (jQuery and Prototype can help you for that), so you guarantee that the Javascript is called when the page has loaded and not before.

You can keep the script in the load method of your control, although really it should be placed in the PreRender because then you can include it or not include it based on the state of the control. This would save you from javascript errors in the future where it says "Object cannot be found" because you have made the control invisible.
The reason you're getting "Sys is not defined" is because your script is being placed before the MicrosoftAjax.js file has loaded. Try something like this:
Dim yourScript as String = "Sys.Application.add_load(function() { /*code here*/ } )"
ScriptManager.RegisterStartupScript(Page, Me.GetType(), "ScriptKey", yourScript, true)
Otherwise you could use Page.ClientScript to hook into the document ready event if using the Sys namespace is not a requirement, but it sounds like from your question it is.
Edit:
Instead of RegisterStartupScript you're probably looking for RegisterClientScriptBlock, sorry, the two have different functionality.

Related

ASP.NET Script after partial postback

I have a web page to modify a script that show the weather info of a certain city.
In this page, users can change the city by loading a different script. This script is copied from a weather site, as a widget.
I have this line to show the weather:
<asp:Literal ID="ltWeatherScript" runat="server" Text='<%# Eval("WeatherScript") %>'>
</asp:Literal>
Where "WeatherScript" is the script that shows the weather.
The problem is when the page has a partial postback, the script doesn't work anymore until I reload the page.
The script could be, for example, this one:
script type="text/javascript" src="http://tiempo.meteored.com/wid_loader/50a0f88ef4aae65daacf31e7a4b1b0fe"
Do you know how to solve this?
I did checked the JS.
this lines are the only suspects to cause problem.
conte = document.getElementById('cont_50a0f88ef4aae65daacf31e7a4b1b0fe');
enlace = document.getElementById('h_50a0f88ef4aae65daacf31e7a4b1b0fe');
anchor = document.getElementById('a_50a0f88ef4aae65daacf31e7a4b1b0fe');
And you said The problem is when the page has a partial postback, the script doesn't work anymore. So the reason maybe that after postback control's IDs are changing. if you can post a markup that will help to diagnose the problem. as for solution, you have to specify the ClientId of the control. check the link Control.ClientID Property to get more info about this property and how to use it.
You need to get the script you're loading (WeatherScript) to execute again after a partial postback. Since the script is not a function, you'll need to create a function on the page that does the (shivers in horror) eval of the script you've loaded from their website. Then you'll need to invoke that function on page load and partial update.
What method are you using for partial postbacks? Update panels, jQuery/XUI AJAX call, etc? This will help me show you the code you need to add to invoke your new function when the partial postback completes.

Unable to call Javascript from Codebehind

I know my issue is very common and similar types has been asked many times over here, but my problem is somewhat different. I am working on ASP.Net 4.0 web application where on my required page i have ajax toolkit 4 calendar control, toolkitscript manager and few asp controls. Now from that pop up i am doing a save operation on button click. What i want is to close popup window after successful save. Problem is not in saving but after saving , automatically closing the popup screen. I have tried the following ways:
RegisterStartUpScriptBlock(this.GetType,"closeForm","return window.close();") and all other required params
ClientScript.RegisterStartUpScript()--- alongwith params and with both return window.close(); and window.close() also with self.close();
Also i have under the title tag...
I think i have tried all the ways , i can. I feel i am lost. Please help me out....
if your using a script manager on the page...
first create a function to close the calendar in js in your html...
function closeCalendar(){
....
}
then on the codebehind use this to call that js function
string script = string.Format(#"closeCalendar()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
If the popup you mean is the AJAX Toolkit Modal Popup, you can just call popup.Hide(); in codebehind.
If it is a browser window, did you try to remove the return part from your code?
Note that windows.close() will not work unless the popup is opened via window.open();
Also, did you try to just put the script tag inside PlaceHolder control that is hidden (server-side Visible=false) by default and only shown when you need?

What is the best way to programmatically run javascript when an ASP.net page loads?

In my global.asax file for my ASP.net project, I am checking for certain conditions. When those conditions are met, I want to automatically execute javascript code when the page runs.
This is my code:
if condition Then
Response.Write(" < script type=""text/javascript"" > ")
Response.Write(" // Javascript code to do stuff ")
Response.Write(" < /script > ")
End If
While this appears to work to execute the Javascript code, I don't think it's a best practice because this code will preceed all of the HTML of the page that gets loaded.
What is the best way of programmatically tacking on some extra Javascript code to be run when my page loads?
Update Thanks for the answer. Too bad this solution doesn't work from within global.asax. Is there no way to make this happen site-wide? It seems like global.asax would be the logical place to put code that runs with every page... Response.Write works fine in global.asax.
To correctly manage the placement of scripts from server controls or pages, you should use ClientScriptManager.RegisterStartupScript()
You can also use the equivalent method in the ScriptManager if you are using ajax controls in your site: ScriptManager.RegisterStartupScript
These methods take care of outputting your script in the appropriate locations to be run when the document is finished loading. The links posted have some good examples to work from.
Note that you won't be able to use these methods directly from global.asax, as it has no reference to the current page. Global.asax is for hooking events to the HttpApplication pipeline, and is decoupled from the actual HttpHandler such as your Page object. To keep the separation of UI, you'd be better off to do the check in your master page or in some base page class, and output the script from there.
back in the days of asp.net ajax 1.0 we had something called Sys.WebForms.PageRequestManager in the ajax client libraries. Haven't worked with asp.net 3.5 and asp.net ajax, but I am sure it is simply enough to add the asp.net ajax javascript file into your page and you'll be able to make use of it. Check out for an event called pageLoaded event.
ps: this event will fire every time there is a sync or async postback
If you want to do it on every page, put it on your masterpage if you have one.
If not, you can create a base Page class, that inherits from System.Web.UI.Page and extend it to check your conditions & render javascript.
Then in the codebehind of each page, inherit your base Page Class instead of System.Web.UI.Page
public partial class Orders : MyCode.BasePage

JQuery Plugins Not Working Correctly With ASP.NET AJAX's ScriptManager

I am trying to use a jQuery plugin in a control. The pages that the control can be on use partial postbacks via an UpdatePanel. I include jQuery and the plugin during the control's PreRender event like this:
ScriptManager.RegisterClientScriptInclude(
this,
this.GetType(),
"jquery",
"/_infrastructure/javascript/jquery.js"));
ScriptManager.RegisterClientScriptInclude(
this,
this.GetType(),
"jquery.customPlugin",
"/_infrastructure/javascript/jquery.customPlugin.js");
The customPlugin jQuery plugin sets up a new function called "executeCustomPlugin". Later in the PreRender event of the control, I use the plugin on an element on the control:
ScriptManager.RegisterStartupScript(
this,
this.GetType(),
"customPlugin init script",
#"$(document).ready(function() {
$('#elementId').executeCustomPlugin();
});",
true);
However, when it executes, I get the JavaScript error:
$('#elementId').executeCustomPlugin is not a function
It would seem as if the jQuery plugin is never executed at all, but I set up window.alerts in the jQuery.customPlugin.js file, and it is indeed being executed.
Is there a way to fix this problem?
A possible explanation is that your plugin doesn't exist in the DOM prior to the execution of the ScriptManager code.
View the source of the page after it is rendered to the browser and ensure that your custom plugin's script tag is rendered before the javascript that is registered with your script manager.
It turns out that my problem was caused by including jQuery twice. The first jQuery instance was getting the plugin applied, but the second jQuery instance was receiving the call.

Reload external javascript after asynchronous postback via UpdatePanel

I have an external javascript on my page, e.g. something like:
<script src="http://foo.com/script.js" type="text/javascript"></script>
and an UpdatePanel somewhere. The script writes some content, and does this from within an anonymous javascript function in the js file. I.e., there is something like this in the script:
(function(){document.write('content');})();
Whenever the UpdatePanel is updated through asynchronous postback, everything the script did (or any javascript on my page, for that matter) is made undone.
For normal javascript, I would just use:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(myFunction)
to redo all that, but since the function in the script source file is anonymous and called upon definition, I'm SOL! Any ideas?
Note: the external js source is from another domain and its content is out of my control.
Try this
private string _myScript = #"(function (){
var ys = document.createElement('script');
ys.type='text/javascript'; ys.async=true;
ys.src='http://foo.com/script.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ys,s);
});";
Then in your Page_Load
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myScript", _myScript , true);
Ok, the "solution" ("dirty ugly hack", if you prefer) I came up with:
Instead of loading the js file directly, I load it via a wrapper that reads the file, wraps the result in custom javascript that puts the anonymous function in a global array, and call all functions in said array upon load and after each asynchronous postback.
Please don't enter this solutions in any beauty pageants.
The real problem here was that I wasn't using UpdatePanels correctly. If the UpdateMode of all the UpdatePanels on your page are set to Conditional, and your ScriptManager has partial updating enabled, it really shouldn't "[undo] everything the script did".

Resources