Monday, February 21, 2011

AJAX ScriptManager

ScriptManager
The core technology of the whole AJAX paradigm is the XMLHttpRequest object. Any AJAX frameworks you might happen to work with will use this object under the hood. If you end up using a different application programming interface (API), well, its only an abstraction layer built to overcome browser differences and simplify programming.
By this definition, the programming model of AJAX applications seems to be clear and  unquestionable. You write code that captures client-side events, conduct an operation on the server via XMLHttpRequest, get the results, and update the user interface. All the client-side programming is done through JavaScript. XMLHttpRequest is a small but critical object; its a building block and it is essential.
AJAX applications require a change of paradigm and some imagination. When it comes to rewriting Web applications for AJAX, nearly all aspects of the application need to be redesigned, reconsidered, refactored, and often rewritten.  A simpler way to work with AJAX involves using a new set of server controls that surround an area of the page and refresh that independently from the rest of the page. 
A simpler way to AJAX passes through a component that, using XMLHttpRequest, could exchange HTML messages with the Web server having the same page URL as its server-side counterpart. In ASP.NET AJAX, this approach goes under the name of partial rendering. ASP.NET partial rendering is centered around a new container controlthe UpdatePanel controlthat you use to surround portions of existing pages, or portions of new pages developed with the usual programming model of ASP.NET. A postback request that originates within any of these updatable regions is captured by the UpdatePanel control and resolved asynchronously using XMLHttpRequest. In this way, fresh HTML is downloaded for the selected region, bypassing the browser and reducing page flickering.

The ScriptManager Control
ScriptManager is by far the most important control in the server infrastructure of ASP.NET AJAX because it performs a number of essential tasks. For example, the ScriptManager control manages and delivers common script resources, such as the les that form the Microsoft JavaScript client library. It also enables or disables general features such as partial rendering, page method calls, and history management. The ScriptManager is also the component that triggers the creation of JavaScript proxies for invoking Web services and Windows Communication Foundation (WCF) services from within a client page.

Regardless of its numerous capabilities, the ScriptManager control is primarily a helper control made available for the convenience of an army of ASP.NET developers. It represents a sort of declarative interface for a number of common tasks in an ASP.NET AJAX page.
To link the Microsoft JavaScript client library to a page, you can certainly use the <script> tag again and make it point to all theles in the library that you need. However, by simply dropping a ScriptManager control in the page, you have it for free and without needing to have any intimate knowledge of the library details.
The following code shows the simplest and most common way to insert the script manager in an ASP.NET page:

<asp:ScriptManager runat="server" ID="ScriptManager1" />

The control produces no user interface, works exclusively on the server, and doesn’t add any extra bytes to the page download.

The control should be considered as a sort of script console in the page; as such, you don’t need to have multiple instances of it in the same page. If multiple script managers are defined in the same page, you are going to get an exception.

The best practice is to place ScriptManager in the master page using the most common conguration. Next, when you need to write a content page that requires different settings, you get a proxy for the manager and enter changes through the proxy. The proxy is a control named ScriptManagerProxy. From a syntax standpoint, its allowed to have ScriptManager in the master and ScriptManagerProxy in the content page. And the proxy can overwrite settings defined in the manager. Note, though, that the ScriptManagerProxy supports only a subset of the properties dened on the ScriptManager control. To override just one of the managers properties that are not replicated through the proxy, you might want to write some code in the Page_Load event of the page and access the local script manager instance through the following code:
// Find a reference to the script manager defined for this page
ScriptManager proxy = ScriptManager.GetCurrent(this);
Once you hold the reference to the real manager, you can enter your changes safely. Note that the same ScriptManagerProxy control uses this technique internally.

Partial Rendering

The ScriptManager control  organizes partial rendering. It exposes a Boolean propertythe EnablePartialRendering propertythrough which developers can enable and disable partial rendering on a given page. Partial rendering is enabled by default. As a result, the ScriptManager injects ad hoc pieces of script code in the HTML of the host page to initialize the partial rendering, client-side engine.

In addition, the ScriptManager control exposes a server-side interface for various tasks related to partial rendering. For example, it offers a propertythe AsyncPostBackSourceElementID propertyto check whether the current postback is because of a standard ASP.NET request
Or a partial rendering request. Likewise, it lets you set a timeout for the partial rendering operation and offers to capture any resulting exception.

The ScriptManager also lets you programmatically register triggers for updatable panels, and it supplies a mechanism to return server-generated data along with the updated markup. Finally, the script manager is also responsible for coordinating the process that generates the fragment of fresh HTML to send to the requesting browser.

Adding Service References to Pages

The ScriptManager control also plays a role in creating the conditions for some client-side JavaScript function to invoke a remote Web or WCF service. The Services section of the control hosts references to .asmx or .svc endpoints that refer to ASP.NET XML Web services and WCF services, respectively.

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/LiveQuotes.svc" />
<asp:ServiceReference Path="~/DataService.asmx" />
</Services>
</asp:ScriptManager>

The Services section also has a programmatic counterpart in the Services collection exposed by the ScriptManager control.

Defining History Points within Pages

An AJAX application tends to replace classic URL-to-URL browser  navigation with script-driven HTTP requests. The history feature of an AJAX application doesn’t necessarily coincide with the list of visited URLs. More likely, the history of an AJAX application is a list of action points scattered through one or a few pages. In a nutshell, AJAX breaks the assumption that the previous state of a Web application coincides with the previously visited URL.

The net effect is that all the user interaction with an AJAX page produces a single entry in the browsers history. Hence, when you click the Back button you are redirected to the previously visited distinct URL, which might be an entirely new page—even a page in a different application.

Theres no simple solution to this problem; there are only hacks to work around it. The most common hack that works is adding a hash string to the URL whenever the page moves to a state that you want to track. A hash is a string appended to the URL prexed by a pound sign (#) symbol. Heres a sample AJAX-trackable URL:


When you change the URL to simply add or modify a hash, the browser doesn’t navigate away from the current page. In addition, it also adds the new URL to its history list. As a result, the user now can navigate back and forward to the URL with the hash and can even bookmark it.

Adding a hash to the current URL at a given point is a practice referred to asadding a history point.” A history point refers to a state of the page that is significant for the page and the application. This state is so signicant that you want to bookmark it for a future reference. For example, if you offer a pageable control such as a DetailsView, any page change is a possible history point. Heres the corresponding code:

protected void DetailsView1_PageIndexChanged(object sender, EventArgs e)
{
// Get significant information to create the hash (that is, the page index)
string state = (sender as DetailsView).PageIndex.ToString();

// Add the history point(s) (Name/Value) ScriptManager.GetCurrent(this).AddHistoryPoint("s", state);


}

A history point is a set of name/value pairs, where the name is an arbitrary but unique string and the value is a string-based representation of any information that will let you restore the bookmarked state.

Whenever the browser navigates to a URL with an attached hash, the ScriptManager control detects it and res a Navigate event. By handling this event, you read the hash, gure out the page state to restore, and restore it.

protected void ScriptManager1_Navigate(object sender, HistoryEventArgs e){
string key = e.State.AllKeys[0]; // First key string state = String.Empty;

if (String.Equals(key, "s"))
{
// Get the hash and convert to an integer (uses an extension method)
state = e.State[key];
int pageIndex = state.ToInt32();

// Restore the state
DetailsView1.PageIndex = pageIndex;
}
}

In classic Back/Forward navigation, the browser retrieves and restores the page. In AJAX navigation, the browser can provide us only with the hash string we associated with a visited pseudo-URL. Its up to the page to re-create the desired state based on the information stored in the hash.

History management is disabled by default. To turn it on, you must set the property EnableHistory of the ScriptManager to true. Finally, note that in ASP.NET AJAX managing history also can be done from within JavaScript in the client side.








No comments:

Post a Comment