IntroductionMicrosoft’s ASP.NET

Lượt xem: 92,388Lượt tải: 9Số trang: 17

Mô tả tài liệu

Microsoft ASP.NET công nghệ mang lại một mô hình lập trình hướng đối tượng và hướng sự kiện và kết hợp nó với những lợi ích của mã biên dịch. Tuy nhiên, mô hình xử lý phía máy chủ của nó có một số nhược điểm vốn có trong công nghệ: thông tin cập nhật Trang yêu cầu một chuyến đi vòng quanh các máy chủ, đòi hỏi một sự làm mới trang. Vòng chuyến đi làm không tồn tại bất kỳ tác dụng tạo ra bởi Javascript hoặc công nghệ phía máy khách khác (chẳng hạn như Adobe Flash)...

Tóm tắt nội dung

ASP.NET brings an and model and unites it with the benefits of compiled code. However, its model has several drawbacks inherent in the Page updates require a to the server, which requires a page refresh. do not persist any effects generated by or other (such as Adobe Flash) During postback, browsers other than Microsoft Internet Explorer do not support restoring the scroll position. And even in Internet Explorer, there is still a flicker as the page is Postbacks may involve a high amount of bandwidth as the form field may grow, when dealing with controls such as the GridView control or There is no unified model for accessing Web Services through or other Enter ASP.NET AJAX AJAX, which stands for And XML, is an framework for providing page updates via composed of code the Microsoft AJAX and a script component called the Microsoft AJAX Script Library. The ASP.NET AJAX also provide support for accessing ASP.NET Web Services via This examines the partial page updates of the ASP.NET AJAX which includes the the control, and the control, and considers scenarios in which they should or should not be utilized. This is based on the Beta 2 release of the Visual Studio 2008 and the .NET 3.5, which the ASP.NET AJAX into the Base Class Library (where it was an add-on component available for ASP.NET 2.0). This also assumes that you are using Visual Studio 2008 and not Visual Web Express Edition; some project templates that are may not be to Visual Web Developer Express users. Partial Page Updates Perhaps the most visible feature of the ASP.NET AJAX is the ability to do a partial or page updates without doing a full postback to the server, with no code changes and minimal markup changes. The are extensive – the state of your (such as Adobe Flash or Windows Media) is bandwidth costs are and the client does not the flicker usually with a The ability to integrate partial page rendering is into ASP.NET with minimal changes into your project. Partial Rendering into an Existing Project Please note: this creates a Web Site project in Visual C#. Code files are in both Visual C# and Visual Basic; however, markup files will only be listed with their C# You may need to adjust @Page 1.) In Microsoft Visual Studio 2008, create a new ASP.NET Web Site project by going to File  New  Web Site… and selecting “ASP.NET Web Site” from the dialog. You can name it whatever you like, and you may install it either to the file system or into Internet Services (IIS). 2.) You will be presented with the blank default page with basic ASP.NET markup (a form and an @Page Drop a Label called Label1 and a Button called Button1 onto the page within the form element. You may set their text to you like. 3.) In Design view, Button1 to generate a event handler. Within this event handler, set to “You clicked the button!”. Listing 1: Markup for before partial rendering is enabled <%@ Page %> html PUBLIC XHTML 1.0 <html > <head </head> <body> <form <div> is a Me" /> </div> </form> </body> </html> Listing 2: (trimmed) in public partial class _Default : { protected void sender, EventArgs e) { = "You clicked the button!"; } } 4.) Press F5 to launch your web site. Visual Studio will prompt you to add a file to enable do so. When you click the button, notice that the page refreshes to change the text in the label, and there is a brief flicker as the page is redrawn. 5.) After closing your browser window, return to Visual Studio and to the markup page. Scroll down in the Visual Studio toolbox, and find the tab labeled “AJAX (If you do not have this tab because you are using an older version of AJAX or Atlas refer to the for the AJAX toolbox items later in this or install the current version with the Windows Installer from the website). a. Known Issue: If you install Visual Studio 2008 Beta 2 onto a computer that already has Visual Studio 2005 installed with the ASP.NET 2.0 AJAX Visual Studio 2008 will import the “AJAX toolbox items. You can whether this is the case by examining the tooltip of the they should say “Version”. If they say “Version,” then you have your old toolbox items, and will need to manually import them by using the “Choose Toolbox Items” dialog in Visual Studio. You will be unable to add Version 2 controls via the designer. 6.) Before the tag begins, create a line of and on the control in the toolbox. Note that a new @Register directive is included at the top of the page, that controls within the namespace should be imported using the asp: prefix. 7.) Drag the closing tag past the end of the Button element, so that the element is with the Label and Button controls wrapped. 8.) After the opening tag, begin opening a new tag. Note that prompts you with two options. In this case, create a tag. Be sure to wrap this tag around your Label and Button so that the markup is 9.) Anywhere within the <form> element, include a control by on the item in the toolbox. 10.) Edit the tag so that it includes the attribute Listing 3: Markup for with partial rendering enabled <%@ Page %> <%@ Register %> html PUBLIC XHTML 1.0 <html > <head </head> <body> <form <div> is a Me" /> </div> </form> </body> </html> 11.) Open your file. Notice that Visual Studio has added a reference to a. What’s New in Visual Studio 2008: The that comes with the ASP.NET Web Site project templates includes all necessary to the ASP.NET AJAX and includes commented sections of that can be to enable Visual Studio 2005 had similar templates when ASP.NET 2.0 AJAX were However, in Visual Studio 2008, the AJAX are opt-out by default (that is, they are by default, but can be removed as 12.) Press F5 to launch your website. Note how no source code changes were required to support partial rendering – only markup was changed. When you launch your website, you should see that partial rendering is now enabled, because when you click on the button there will be no flicker, nor will there be any change in the page scroll position (this example does not that). If you were to look at the rendered source of the page after clicking the button, it will confirm that in fact a post-back has not – the original label text is still part of the source markup, and the label has changed through Visual Studio 2008 Beta 2 does not appear to come with a template for an ASP.NET web site. However, such a template was available within Visual Studio 2005 if the Visual Studio 2005 and ASP.NET 2.0 AJAX were a web site and starting with the Web Site will likely be even easier, as the template should include a file all of the ASP.NET AJAX including Web Services access and JSON – Object Notation) and includes an and within the main Web Forms page by default. Enabling partial with this default page is as simple as Step 10 of this and dropping controls onto the page. The Control Control Reference Name Type Bool Specifies whether to use the custom error section of the file to handle errors. String Gets or sets the error message sent to the client if an error is raised. Int32 Gets or sets the default amount of a time a client should wait for the request to complete. Bool Gets or sets whether script is enabled. Bool Gets or sets whether script is Int32 the number of seconds allowed for loading scripts into the client Enum (Auto, Debug, Release, Gets or sets whether to render release of scripts String Gets or sets the root path to the location of script files to be sent to the client. Name Type Gets details about the ASP.NET Service proxy that will be sent to the client. Bool Gets whether script and code is enabled. Bool Gets whether the page is in an post back request. Gets details about the ASP.NET Service proxy that will be sent to the client. Scripts Gets a of script that will be sent to the client. Gets a of Web Service proxy that will be sent to the client. Bool Gets whether the current client partial If this returns false, then all page requests will be standard Public Code Methods: Method Name Type Void Sets the focus of the client to a control when the request has Markup Tag Provides details about the proxy to the ASP.NET service. Provides details about the proxy to the ASP.NET profiling Provides script Denotes a specific script Provides Web Service which will have proxy classes Denotes a specific Web Service The control is the essential core for the ASP.NET AJAX It access to the script library the extensive script type supports partial and provides extensive support for ASP.NET services (such as and but also other Web The control also provides and support for the client scripts. and Scripts While the Microsoft ASP.NET 2.0 AJAX include the entire script code in both debug and release editions as resources embedded in the are free to redirect the to script files, as well as necessary scripts. To override the default binding for the scripts (such as those which support the namespace and the custom typing system), you can register for the event of the class. When this method is called, the event handler has the to change the path to the script file in the script manager will then send a different or copy of the scripts to the client. script by the class) can be included or via markup. To do so, either modify the or include tags under the <Scripts> tag, which is a child of the control. Custom Error Handling for updates are handled by triggers specified by controls, the support for error handling and custom error messages is handled by a page’s control instance. This is done by exposing an event, to the page which can then provide custom logic. By consuming the event, you may specify the property, which then causes an alert box to be raised upon of the callback. is also possible instead of using the default alert box; for instance, you may want to display a <div> element rather than the default browser modal dialog. In this case, you can handle the error in client script: Listing 5: script to display custom errors <script <!-- args) { if != { var = “”; if == “200”) { = } else { // the server wasn’t the = “An unknown error } // do something with the here. // now make sure the system knows we handled the error. } } // --> Quite simply, the above script registers a callback with the AJAX runtime for when the request has been It then checks to see whether an error was reported, and if so, processes the details of it, finally to the runtime that the error was handled in custom script. and Support The control provides extensive support for of script strings and user interface however, that topic is outside of the scope of this For more see the Support in ASP.NET AJAX The Control Control Reference Name Type bool Specifies whether child controls invoke refresh on postback. enum (Block, Inline) the way the content will be visually enum (Always, whether the is always during a partial render or if it is only refreshed when a trigger is hit. Name Type bool Gets whether the is partial rendering for the current request. ITemplate Gets the markup template for the update request. Control Gets the template for the update request. Gets the list of triggers with the current Public Code Methods: Method Name Type Void Updates the specified Allows a server request to trigger a partial render of an Markup Tag Specifies the markup to be used to render the partial result. Child of Specifies a of n controls with this Child of Specifies a trigger that invokes a partial page render for the given This may or may not be a control as a of the in question. to the event name. Child of Specifies a control that causes the entire page to refresh. This may or may not be a control as a of the in question. Granular to the object. Child of The control is the control that delimits the content that will take part in the partial rendering of the AJAX There is no limit to the number of controls that can be on a page, and they can be nested. Each is isolated, so that each can work (you can have two running at the same time, rendering different parts of the page, of the page’s The control primarily deals with control triggers – by default, any control within an that creates a postback is as a trigger for the This means that the can work with the default controls (such as the with user controls, and they can be in script. By default, when a partial page render is all controls on the page will be whether or not the controls defined triggers for such action. For example, if one defines a Button control, and that Button control is all controls on that page will be refreshed by default. This is by default, the property of the is set to Always. you may set the property to which means that the will only be refreshed if a specific trigger is hit. Custom Control Notes An can be added to any user control or custom control; however, the page on which these controls are included must also include a control with the set to true. One way in which you might account for this when using Web Custom Controls is to the protected method of the class. By doing so, you can inject an between the control’s children and the outside world if you determine the page supports partial you can simply layer the child controls into a container Control instance. The operates as something of a wrapping ASP.NET postbacks within the context of a However, there are to bear in mind, both in terms of behavior and speed. To how the works, so that you can best decide when its use is you should examine the AJAX exchange. The following example uses an site and, Mozilla Firefox with the Firebug extension (Firebug captures data). a form that, among other things, has a postal code textbox which is supposed to a city and state field on a form or control. This form collects including a user’s name, address, and contact There are many design to take into account, based on the of a specific project. In the original iteration of this a control was built that the entirety of the user data, including the postal code, city, and state. The entire control was wrapped within an and dropped onto a Web Form. When the postal code is entered by the user, the detects the event (the event in the back-end, either by triggers or by using the property set to true). AJAX posts all of the fields within the as captured by FireBug (see the diagram on the right). As the screen capture values from every control within the are (in this case, they are all empty), as well as the ViewState field. All told, over 9kb of data is sent, when in fact only five bytes of data were needed to make this request. The response is even more bloated: in total, 57kb is sent to the client, simply to update a text field and a drop-down field. It may also be of interest to see how ASP.NET AJAX updates the The response portion of the update request is shown in the Firebug console display on the left; it is a string that is broken up by the client script and then on the page. ASP.NET AJAX sets the property of the HTML element on the client that your As the browser the DOM, there is a slight delay, depending on the amount of that needs to be The of the DOM triggers a number of issues: If the focused HTML element is within the it will lose focus. So, for users who pressed the Tab key to exit the postal code text box, their next would have been the City text box. However, once the refreshed the display, the form would no longer have had focus, and pressing Tab would have started the focus elements (such as links). If any type of custom script is in use that accesses DOM elements, by functions may become defunct after a partial postback. are not intended to be catch-all Rather, they provide a quick for certain including small control updates, and provide a familiar interface to ASP.NET who might be familiar with the .NET object model but less-so with the DOM. There are a number of that may result in better depending on the scenario: Consider using and JSON Object Notation) allows the to invoke static methods on a page as if a web service call was being invoked. Because the methods are static, no state is the script caller supplies the and the result is returned Consider using a Web Service and JSON if a single control needs to be used in several places across an This again requires very little special work, and works through Web Services or Page Methods has drawbacks as well. First and foremost, ASP.NET typically tend to build small of into user controls (.ascx files). Page methods cannot be hosted in these files; they must be hosted within the actual .aspx page class. Web services, must be hosted within the .asmx class. Depending on the this may violate the Single in that the for a single is now spread across two or more physical which may have little or no cohesive ties. if an requires that are used, the following should assist with and Nest as little as possible, not only but also across units of code. For example, having an on a Page that wraps a Control, while that Control also contains an which contains another Control that contains an is nesting. This helps to keep clear which elements should be and prevents refreshes to child Keep the property set to false, and set events. the is a much clearer way to handle events, and may prevent behavior, helping with tasks and forcing a developer to “opt-in” for an event. Use the smallest possible unit to achieve As noted in the of the postal code service, wrapping only the bare minimum reduces time to the server, total and the footprint of the exchange, enhancing The Control Control Reference Name Type String Specifies the ID of the that this should report on. Int Specifies the timeout in before this control is displayed after the request begins. bool Specifies whether the progress is rendered Markup Tag Contains the control template set for the content that will be with this control. The control gives you a measure of feedback to keep your users’ interest while doing the necessary work to transport to the server. This can help your users know that you’re doing something even though it may not be apparent, since most users are used to the page and seeing the status bar As a note, controls can appear anywhere on a page However, in cases in which a partial postback is initiated from a child (where an is nested within another postbacks that trigger the child will cause templates to be displayed for the child as well as the parent But, if the trigger is a direct child of the parent then only the templates with the parent will be Summary The Microsoft ASP.NET AJAX are products designed to assist in making web content more and to provide a richer user to your web As part of the ASP.NET AJAX the partial page rendering including the the and controls are some of the most visible of the toolkit. The component the provision of client for the as well as enables the various server- and to work with minimal The control is the apparent magic box – markup within the can have and not trigger a page refresh. controls can be nested, and can be dependent on controls in other By default, handle any postbacks invoked by their controls, although this can be finely tuned, either or When using the control, should be aware of the impact that could arise. Potential include web services and page though the design of the should be The control allows the user to know that she or he is not being ignored, and that the request is going on while the page is otherwise not doing to respond to the user input. It also includes the ability to abort partial results. these tools assist creating a rich and seamless user by making server work less apparent to the user and workflow less. Bio Scott Cate has been working with Microsoft Web since 1997 and is the of where he in writing ASP.NET based focused on Knowledge Base Software Scott can be contacted via email at or his blog at