ASP. NET Ajax Learning (1) server side

Source: Internet
Author: User
Tags net return

The ASP. NET Ajax framework provides two development models: server-side programming and client-side programming. The former is easy to use, developers do not understand JS and Ajax, but through the traditional ASP. NET Development Method to complete Ajax application development, but its control granularity is coarse, he is more suitable for local asynchronous refresh on existing systems. The latter is relatively difficult to develop and requires developers to be familiar with JavaScript and ASP. net ajax provides various syntax support and client programming models, but its fine-grained control is conducive to improving application performance and quality.

We can develop Ajax programs without any Ajax framework. The core of Ajax is the XmlHttpRequest object, but it is very troublesome to develop Ajax programs without framework, you must create different XmlHttpRequest Objects Based on different browser objects, define the callback function, implement logic in the callback function, and send asynchronous requests.

MS implements an Ajax framework based on the complex work described above, even if ASP. net Ajax framework, which has been integrated with the VS2008 development environment, and an ASPAJAXExtSetup needs to be installed in VS2005. msi and perform Web. to implement ASP. net Ajax framework. With the ASP.net Ajax framework, we can use WebService in JavaScript to call the background. CS file code.

Part 1 Server 

I.Asp.net AjaxBasic knowledge 

The installation package of Microsoft ASP. Net Ajax includes the following parts:

I. ASP. NET 2.0 AJAX ExtensionsThe core part of asp.net ajax includes the most important and basic controls, components, and functions, such as the ScriptManager control and UpdatePanel control on the server, the client's JavaScript object-oriented extensions, debugging, and Web Service proxies.

Ii. ASP. net ajax Futures CTPThe non-core components of asp.net ajax include Extender Control on the server side, Web Components, various controls on the client side, implementation of drag-and-drop functions, and ASP.. net ajax xml scripts. The client components include animation components, behavior components, and validators. The client controls include space such as ListView, Hyperlink, selector, Button, and Label. The style extender controls on the server side include DragoverlayExtender ..

Iii. Microsoft AJAX LibraryContains ASP. net ajax client JavaScript file, which contains the js file is Extensions. dll and preview. A collection of js files included in the dll. You can use this installation file when you do not need the asp.net ajax framework. Otherwise, you do not need to install Extensions. dll and preview. dll includes all the client scripts in the installation package.

Iv. ASP. net ajax Control ToolkitContains dozens of ASP. net ajax-based, componentized ASP. NET Ajax server-side controls and ASP. net ajax extenders that provide a specific AJAX Function

 

Extensions. dllMicrosoft AJAX LibrarySome client jsFile has:

MicrosoftAjax. js: This file contains ASP. net ajax core content and functions, such as JavaScript object-oriented extensions, Error, Type, StringBuilder and other client types, and encapsulation of the XMLHttpRequest object called Web Service). On this basis, it also expands to include the most basic client components/controls, XMLHttpExecutor for asynchronous calls, WebRequest objects, and asp access. NET 2.0 application service, such as ProfileService and AuthenticationService objects ASP. net ajax. This file is also responsible for smoothing the nuances of JavaScript and DOM access between different browsers, in order to provide developers with encapsulated, unified, and standard APIs. Generally speaking, these are all perfect ASP. the functions required by the NETAJAX application. Therefore, by default, ScriptManager uses this file as an ASP. net ajax core script file is sent to the client.

 

MicrosoftAjaxTimer. js: This file defines the Timer component of the client, used in combination with ASP. net ajax Server

Implement the Timer component on the server side to provide the function of regularly triggering events (on the client side and on the server side.

 

MicrosoftAjaxWebForms. js: This file defines a very important client object: PageRequestManager. PageRequestManager is designed to provide developers with a development model with the same lifecycle as the ASP. NET Server Page on the client. It controls and maintains the whole process of client asynchronous delivery in an object-oriented manner. If the support for partial update and asynchronous sending (EnablePartialRendering attribute is set to true) is enabled in ScriptManager, the file is automatically sent to the client. In this script, the UpdatePanel control on the server can work properly.

 

Preview. dllMicrosoft AJAX LibrarySome client jsFiles include:

PreviewScript. js: This file contains ASP. net ajax, includes TextBox that represents a simple interface element, ListView that represents a complex binding list, Validator that verifies user input, Behavior that provides some additional Behavior for HTML elements, offline data source at the client, and response to users actions, and ASP.. net ajax xml script. Similarly, this file also declares the code that is compatible with different browsers.

 

PreviewDragDrop. js: this file is used to provide the Implementation of the mouse drag function in ASP. net ajax.

PreviewWebParts. js and WhidbeyWebParts. js: This file defines and ASP. NET Web parts (WebPart)

Scripts for collaborative work.

PreviewGlitz. js: this file is used to implement special effects on some interfaces, such as fade-in and fade-out, and animated effects.

 

II.ScriptManagerReference script 

The ASP. net ajax assembly System. Web. Extensions. dll and Microsoft. Web. Preview. dll contain

Copy the client script of both Debug and Release versions. ScriptManager will use this part of the resources embedded in the Assembly to generate the script required by the client. The client framework script will not be directly referenced to the client.

By default, ScriptManager automatically sends the MicrosoftAjax. js file and MicrosoftAjaxWebForms. js file to the client. If other ASP. net ajax client script, or some custom script files, you need to manually add references to these files in ScriptManager, if you need to use ASP. functions of some components of net ajax Futures CTP. <asp: ScriptReference Assembly = "Microsoft. web. preview "/> to reference prviewScript. js script file

 

The EnablePartialRendering attribute of ScriptManager is set to true, so that ASP. net ajax will add some additional JavaScript scripts to the page to intercept and implement ASP. NET return function, and then use the XMLHttpRequest object to replace the traditional whole-page delivery, send an asynchronous request to the server

 

3. Client call PAGE Method 

Set the EnablePageMethods attribute of ScriptManager to true, and then define a static method on the server side (note that the method must be static and you must add [System. web. services. webMethod] attribute ):

 

 [System.Web.Services.WebMethod]

public static string SayHello(string name)

{

return string.Format("hello, {0}!", name);

}

 

 

Then you can directly call this method using the following line of statements in the client JavaScript (note that this method is defined in PageMethods ):

PageMethods. SayHello ("Dflying", cb_sayHello );

Cb_sayHello indicates the callback function to be triggered after the asynchronous call is completed.

 

4. Introduce embedded script Resources in the Assembly:

 

 <asp:ScriptManager runat="server">

<Scripts>

<asp:ScriptReference Assembly="Microsoft.Web.Preview" />

</Scripts>

</asp:ScriptManager>

 

 

The Value-add script of ASP. net ajax must be added to the page in this way.

 

5. Introduce a separate script file:

 

 <asp:ScriptManager runat="server">

<Scripts>

<asp:ScriptReference Path="MyPath/MyCustomScript.js" />

</Scripts>

</asp:ScriptManager>

 

 

<Scripts> multiple <asp: ScriptReference> can be defined under the tag, representing different Scripts respectively.

 

6. The sameScriptManagerIntroduce differentDebugVersion andReleaseVersion File 

The ScriptManager control naturally takes this requirement into consideration during design. It provides an enumerative attribute named ScriptMode, it indicates whether the scriptmanager sends the debug or release js script file to the client each time. However, in some cases, we may want a script not to use the global settings of the entire ScriptManager. For example, ScriptManager specifies the script using the Release version, but we want a script to use the Debug version for debugging. In this case, we can use <asp: scriptReference> the Same Name attribute in the tag (Note: it is not the <asp: ScriptManager> tag) -- ScriptMode to overwrite the settings defined in ScriptManager. The default value is Inherit, which indicates inheriting the global settings in ScriptManager. Note that if the Machine of the website deployment environment is. if the retail attribute of the <deployment> element in the config file is set to true, no matter how you set the ScriptMode attribute in <asp: ScriptManager> and <asp: ScriptReference>, all ScriptManager scripts of the Release version will be sent directly.

 

ScriptManager will trigger the ResolveScriptReference event when parsing every Script. In the server-side scriptmanager‑resolvescriptreference () function, we can obtain the ScriptReference object to be parsed through the e. Script parameter.

 

The LoadScriptsBeforeUI Boolean attribute of the ScriptManager control can be used to set ASP. the location where the net ajax script file appears on the final HTML page. The default value is true, indicating that the reference (that is, the <script> tag) of the script file will appear before all HTML elements on the interface, this ensures that ASP is loaded and initialized when the page is displayed. net ajax client framework, and users can immediately start using this program

 

7.ScriptManagerIntroduce scripts to support localization 

To use the built-in localization function of ScriptManager, pay attention to the following points:

(1) The EnableScriptLocalization attribute of ScriptManager must be set to true.

(2) You must use ScriptPath to directly introduce the script, instead of using the Assembly and Name attributes to introduce the script embedded in the Assembly.

(3) Make sure that all the regions specified by the ResourceUICultures attribute have a script file that matches it. For example, in the above example, the ResourceUICultures attribute is set to zh-CN and en-US, then we need to ensure that the website has given the Scripts/MyControl. zh-CN.js and Scripts/MyControl. en-US.js Scripts.

 

8. Notification that script resources are loaded:

On the ASP. net ajax page, the end of each script file to be run in collaboration with the client framework must contain the following code to send this notification: if (typeof (Sys )! = "Undefined") Sys. Application. policyscriptloaded (); therefore, when writing a custom script file, add the above line at the end. The script file is embedded in a program set and introduced through the Assembly and Name attributes of <asp: ScriptReference>. net ajax will automatically add the above statement at the end of the file to notify the script resource loading is completed. If the script file already has this line, this line of code will be executed twice, causing an exception. To solve this problem, <asp: ScriptReference> specifically introduced the NotifyScriptLoaded Boolean attribute. The default value is true, that is, the statement indicating that script resources are loaded is automatically added to the script embedded in the Assembly.

 

9. ManagementWebserviceClient proxy: 

<Asp: ServiceReference> the TAG provides a Boolean attribute: InlineScript. The default value is

False. If it is set to true, the client proxy of the Web Service will not be obtained separately through the form of "Web Service file path +/js (or jsdebug) Suffix, instead, it is embedded in the HTML code of the page and sent to the client together, that is, "inline (inline )". Generally, because the proxy files on the Web Service client are relatively small, there is not much time to transfer files, therefore, the necessary preparation for transferring this file-the time it takes to establish and close an HTTP connection to request this proxy file, the time spent on the entire HTTP request also occupies a relatively large proportion. If you inline it into the page like this, you can avoid this additional HTTP request, which slightly improves the page loading performance.

 

10. Exception Handling: 

A very important attribute of the ScriptManager control: AllowCustomErrorsRedirect. This attribute is of the boolean type. The default value is true, indicating whether to use the settings in the Web. config <customErrors> section in the case of an asynchronous update exception. You can specify the application-level error handling page in the <customErrors> section of Web. config. This will be achieved by redirecting to a page that specifically displays exceptions. For Ajax programs, page Jump should be avoided. Therefore, it is best to set it to false.

The AsyncPostBackError event of ScriptManager will be triggered when an exception occurs during asynchronous delivery. The AsyncPostBackErrorMessage attribute indicates the message displayed when an exception occurs during asynchronous delivery.

 

11th.Control by programmingScriptManager: 

ScriptManager provides a method named RegisterAsyncPostBackControl (). This method accepts a Control-type parameter. With this method, the value of the EnablePartialRendering attribute of ScriptManager must be set to true.

The content enclosed in UpdatePanel and its specified control as the trigger are automatically registered in ScriptManager for asynchronous delivery, without manual intervention. To modify attributes such as EnablePartialRendering, EnableScriptGlobalization, EnablePageMethods, and EnableScriptLocalization of ScriptManager, it is best to modify these attribute values in the PreInit event handler function of Page. If it is later than this stage, ScriptManager may throw an exception.

 

ScriptManager also provides a read-only Boolean attribute: IsInAsyncPostBack. Similar to judging whether the code executed by the current server is triggered by sending back by the Page. IsInAsyncPostBack attribute in the traditional ASP. NET model, IsInAsyncPostBack can be used to determine whether the code executed by the current server is triggered by asynchronous sending back.

 

Code

 Protected void Page_Load (object sender, EventArgs e)

{

ScriptManager theScriptManager = ScriptManager. GetCurrent (this );

If (theScriptManager. IsInAsyncPostBack)

{

// Only the code that is executed in asynchronous sending.

}

}

 

 

The Boolean attribute SupportsPartialRendering of ScriptManager is used to determine whether the current browser supports Ajax partial update. The Boolean attribute IsDebuggingEnabled of ScriptManager is used to determine whether the current request runs in Debug mode; the Scripts and Services Attributes provided by ScriptManager will return the script file referenced in the current ScriptManager object and the Web Service set respectively, it also provides a large number of other ASP. net ajax controls, script blocks, and data methods all start with "Register.

 

When the scriptManager control is used on the template page and other scripts need to be referenced on the page where the template page is applied, you can use the scriptManagerProxy control on the page, this control can also introduce script files and webservice, which are no different from the scriptmanager control.

12th. UpdatepanelIntroduction

Implementation principle of updatePanel: first, scriptManager and updatePanel reach an agreement on the server side to intercept page Render () method and outputs some js footsteps specially used for partial refresh on the page for the controls that require asynchronous sending back, and then on the client, if these controls pass through _ doPostBack () if the function tries to trigger the whole page delivery, the js step mentioned above will intercept this call and add the value of the control input by each user on the page to the current ViewState) use the xmlhttpRequest object to send it back to the server. At this time, the server does not know this, but still regards it as a traditional delivery, which leads to a full page lifecycle and generates a new page structure based on the delivery, later, in the page Render () method, scriptmanager and updatePanel intercepted the implementation process again, removed all content not in UpdatePanel, and only sent to the client for the truly updated part. Finally, the xmlHttpRequest object of the client receives this part of information and quietly updates the content defined in UpdatePanel.

 

On the client side, updatePanel is rendered as a pair of div elements by default. If the renderMode attribute of updatePanel is set to inline, updatePanel is displayed as a span element on the client. UpdatePanel also has a read-only attribute: IsInPartialRendering. Because it is read-only, it is only used in the server code. It is only used in asynchronous delivery, and the content in updatePanel will be updated to true only when it is updated;

 

UpdatePanel can call its update () to force it to refresh.

If the childrenAsTriggers attribute of updatePanel is set to false, the updatePanel's updateMode attribute must be Conditional. If it is always, the program will throw an exception at runtime.

 

Note: During asynchronous delivery, all form fields (including viewState) of the entire page will be completely sent back to the server. Therefore, before the Server Render step, there is no difference between asynchronous delivery and the traditional full-page delivery. The server will still perform Init, Load, event processing, and other steps, you can also access any attributes of any controls on the page, whether or not they are in an updatePanel. Of course, the server can also set attributes of a control other than updatePanel during asynchronous delivery, this change is not sent back to the client in the render step, so the client cannot see this change.

 

Asp.net ajax also adds several events to the client for asynchronous delivery, including initialize_Request, beginRequest, pageLoading, pageLoaded, and endrequest, this gives the client a similar concept of server lifecycle. This is implemented with the client's PageRequestmanager object.

 

When a user control with updatePanel is dynamically loaded, it must be carried out in the Page_Init event, not in PageLoad, because scriptmanager and updatepanel are coordinated and communicated in the pageLoad event, this allows the client to send js scripts that support partial updates.

The dynamic loading control can be as follows:

 

 page.LoadControl("aaa.ascx");

page.controls.Add("aaa.ascx");

 

In the next article, we will introduce the client section of ASP. NET Ajax.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.