asp.net ajax 2

Dynamically Assigning ASP.NET AJAX Script References

Introduction

In most scenarios, the easiest way to add a script file to an ASP.NET page is in markup, as in the following example:

<asp:ScriptManager ID="SMgr" runat="server">
  
<Scripts>
    
<asp:ScriptReference Path="./Script.js" />
  
</Scripts>
</asp:ScriptManager> 

However, it is also possible to add script references dynamically.
Page developers can do this to have more control over how a script is added. For example, they might add scripts dynamically to help conserve memory resources by not loading a large script library unless it is needed. Or they might load different versions of scripts for different types of users.
Control developers add scripts dynamically when they create script controls or extender controls in order to make script resources automatically available to the page that hosts the control. ( what this sentence mean --to Control Developer wp.)

This topic addresses a simple page developer scenario. For adding script references in custom controls, see Adding Client Behaviors to Web Server Controls by Using ASP.NET AJAX Extensions.

Script references can specify script files or scripts embedded as resources in assemblies. Scripts can exist in debug and retail versions. The following procedure shows how to assign a script reference to a page in each of these situations.


note

All script files to be registered with the ScriptManager control must call the notifyScriptLoaded method to notify the application that the script has finished loading. (But ? wp.)Assembly-based scripts should not call this method in most cases. For more information, see notifyScriptLoaded Method.

To dynamically add a script reference to a page

1.If you do not know the ID of the <asp:ScriptManager> element on the page, call the GetCurrent() method of the ScriptManager control(not ScriptManager1 wp.)  to get the current instance of the control. Test for null in case there is no ScriptManager control on the page. If you know that there is an <asp:ScriptManager> element on the page and you know its ID value, you can skip this step.

The following example shows how to test for the existence of a ScriptManager control on a page, and then either get the current instance or create a new instance.

// If there is a ScriptManager on the page, use it.
// If not, throw an exception.
ScriptManager Smgr = ScriptManager.GetCurrent(Page);
if (Smgr == nullthrow new Exception("ScriptManager not found.");
2.Create a ScriptReference object.
ScriptReference SRef = new ScriptReference();
3.For file-based scripts,
if you know that the ScriptPath property of the ScriptManager control is set to the correct location for the script file, set the Name property of the ScriptReference instance to the name of the script file.

posted on 2007-10-31 17:48  simhare  阅读(179)  评论(0)    收藏  举报

导航