Microsoft Virtual Labs

scaredbaconΛογισμικό & κατασκευή λογ/κού

4 Ιουλ 2012 (πριν από 5 χρόνια και 1 μήνα)

340 εμφανίσεις

Introduction to ASP.NET AJAX 3.5 SP1


Microsoft
®

Virtual Labs
Introduction to ASP.NET AJAX 3.5 SP1
Table of Contents
Introduction to ASP.NET AJAX 3.5 SP1 ................................................................................... 1
Exercise 1 Adding History Points to an ASP.NET AJAX Web Application Using Server Controls ............................ 2
Exercise 2 Adding History Points to an ASP.NET AJAX Web Application Using the AJAX API .............................. 7
Exercise 3 Verify Your Steps ...................................................................................................................................... 11
Introduction to ASP.NET AJAX 3.5 SP1
Page 3 of 13
Tasks
Detailed Steps
b. Handle the OnClick event of the link that displays the animal image. To do this,
add the code shown in bold to the ImageLink LinkButton definition:
</asp:UpdatePanel>

<asp:UpdatePanel ID="infoPanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="AnimalDropDown"
EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="DescriptionContainer"
runat="server"
Visible="false">
<p><asp:Literal ID="AnimalDescription"
runat="server" /></p>
<p><asp:LinkButton ID="ImageLink"
runat="server" Text="Click here to see the image"
OnClick="ImageLink_Click" />
</p>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>

</div>
c. Add the ScriptManager server control that will manage browser history entries
and provide logical navigation. To do this, paste the following code inside the
form element and ensure that it is placed above any UpdatePanel controls.
<div id="container">

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

<asp:UpdatePanel ID="optionPanel" runat="server">
Note: Browsers usually do not offer a programmatic API to manage the URL history
stack. ASP.NET AJAX needs to perform browser-specific tricks that basically involve
forcing the browser to navigate to the URL in a way that is invisible to the user. Thus,
history management is implemented differently for each browser. For Internet
Explorer, for example, an iframe element that downloads the URL is rendered to the
client, which automatically adds this URL to the list of visited URLs. This can result in
additional requests to the server.

d. Set the EnableHistory property of the ScriptManager control to true to enable
history management and indicate that the application will have the ability to add
custom history points. To do this, add the property to the ScriptManager control
inserted before.
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableHistory="True">
</asp:ScriptManager>

Introduction to ASP.NET AJAX 3.5 SP1
Page 4 of 13
Tasks
Detailed Steps
3. Create history points
Note: A history point is a logical navigation point in the Web application that can be
represented through state information. The state information can be used to restore
the Web application to a previous state, either directly with state data or through an
identifier used to retrieve state information that is stored elsewhere.
History points should be added only in response to user actions, such as clicking a
selection, and not as the result of simply running application code.
a. Add code to create a history point when the SelectedIndex of the drop down list
changes. To do this, in Solution Explorer double-click Default.aspx.cs and add
the following code to the AnimalDropDown_SelectedIndexChanged method,
placing the code before the closing brace of the if block (the correct location is
identified in the source file).
if (this.ScriptManager1.IsInAsyncPostBack &&
!this.ScriptManager1.IsNavigating)
{
this.AddHistoryPoint(selectedItem);
}

Note: In this code fragment, the System.Web.UI.ScriptManager.IsNavigating property,
when true, indicates that the postback occurred a result of the user clicking the back
or forward button.
b. Add code to register a history point when the image link button is clicked. To do
this, add the following code to the ImageLink_Click method, placing the code
before the closing brace of the method (the correct location is identified in the
source file).
if (this.ScriptManager1.IsInAsyncPostBack &&
!this.ScriptManager1.IsNavigating)
{

this.AddHistoryPoint(String.Format(CultureInfo.InvariantCu
lture, "{0} Image", selectedItem));
}

c. Add code to save the history points. To do this, replace the body of the
AddHistoryPoint method with the following code:
private void AddHistoryPoint(string historyPointName)
{
NameValueCollection pageState = new
NameValueCollection();
pageState.Add("animalIndex",
this.AnimalDropDown.SelectedIndex.ToString(CultureInfo.Inv
ariantCulture));
pageState.Add("animalDescription",
this.AnimalDescription.Text);
pageState.Add("animalImage",
this.AnimalImage.ImageUrl);

this.ScriptManager1.AddHistoryPoint(pageState,
historyPointName);
}
Note: To create a browser history point, the
System.Web.UI.ScriptManager.AddHistoryPoint method of the ScriptManager control
is called. This method enables you to store key/value pairs in a NameValueCollection
Introduction to ASP.NET AJAX 3.5 SP1
Page 5 of 13
Tasks
Detailed Steps
that identifies the state of your application, along with optional data to represent the
title of the history entry in the browser. The saved data can be used to re-create the
state of the page when a subsequent history navigation event is raised.
There is an additional overload of the ScriptManager.AddHistoryPoint method that
takes a single key/value parameter pair.
4. Restore the page
state
Note: When a user clicks the browser's history navigation buttons, the browser
navigates through previously viewed URLs that contain history point state. Client
code in the Web page detects that the URL contains history state data and makes a
request to the page, passing the state. When server state is detected in a request, the
ScriptManager.Navigate event is raised, which appears like an asynchronous
postback to the server. The Navigate event can be handled to re-create the page based
on state information as required by your Web application.
a. Set the onNavigate event handler in the ScriptManager server control. To do
this, add the code shown in bold to the ScriptManager definition:
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableHistory="True"
onNavigate="ScriptManager1_Navigate">
b. Retrieve the page state from the browser's history stack data in the navigate event.
To do this, in the Default.aspx.cs file, replace the body of the
ScriptManager1_Navigate method with the following code:
protected void ScriptManager1_Navigate(object sender,
HistoryEventArgs e)

{
NameValueCollection pageState = e.State;
string animalIndexString =
pageState.Get("animalIndex");
string animalDescription =
pageState.Get("animalDescription");
string animalImageUrl = pageState.Get("animalImage");
}

Note: History points are stored in the browser's history stack only as URLs. History
state is managed as data in a query string or as a URL fragment value that is marked
with the "#" character. In addition, server state information is appended after the
"&&" separator. The resulting URL is included in the browser's history stack.
Because of size restrictions on URLs (1024 characters max.), the state information
that you create should be as small as possible.
c. Add code to restore the state of the animal drop down list. To do this, paste the
following code inside the ScriptManager1_Navigate method, below the code
inserted in the previous step:
if (string.IsNullOrEmpty(animalIndexString))
{
this.AnimalDropDown.SelectedIndex = 0;
}
else
{
int index = Convert.ToInt32(animalIndexString,
CultureInfo.InvariantCulture);
this.AnimalDropDown.SelectedIndex = index;
}
d. Add code to restore the state of the animal’s description. To do this, paste the
Introduction to ASP.NET AJAX 3.5 SP1
Page 6 of 13
Tasks
Detailed Steps
block shown below following the code inserted in the previous step:
if (string.IsNullOrEmpty(animalDescription))
{
this.DescriptionContainer.Visible = false;
}
else
{
this.DescriptionContainer.Visible = true;
this.AnimalDescription.Text = animalDescription;
}

e. Add code to restore the state of the animal’s image. To do this, paste the block
shown below following the code inserted in the previous step:
if (string.IsNullOrEmpty(animalImageUrl))
{
this.AnimalImage.Visible = false;
}
else
{
this.AnimalImage.Visible = true;
this.AnimalImage.ImageUrl = animalImageUrl;
}

f. Go back to the previous page, by clicking the Back button of the browser.
g. At the bottom of the product table you will see paging controls. These controls
appear when the number of rows is large and let you navigate through pages and
select the number of results per page to be shown.


Introduction to ASP.NET AJAX 3.5 SP1
Page 8 of 13
Tasks
Detailed Steps
<a
href="javascript:getAnimalImage($get('AnimalSelect').selec
tedIndex);"
id="ImageLink" style="visibility: hidden;">Click here to
see the image</a>
c. Set the EnableHistory property of the ScriptManager control to true to enable
history management. To do this, add the following code to the ScriptManager
control definition:
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableHistory="true">
</asp:ScriptManager>
d. Register the Animal Web service in the ScriptManager control to enable calls to
the Web service methods from client script. Paste the following code inside the
ScriptManager control:
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableHistory="true">
<Services>

<asp:ServiceReference Path="~/Services/Animal.svc" />
</Services>
</asp:ScriptManager>
Note: The Animal service located under the Services folder of the solution is a WCF
service. It provides animal descriptions and images paths. Its configuration can be
found under the <system.serviceModel> tag in Web.Config.
e. Register the script file main.js in the ScriptManager control to make it available
on the client side. Paste the following code inside the ScriptManager control:
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableHistory="true">
<Services>
<asp:ServiceReference Path="~/Services/Animal.svc"
/>
</Services>
<Scripts>
<asp:ScriptReference Path="~/Scripts/main.js" />
</Scripts>
</asp:ScriptManager>
3. Create history points
Note: In this task you will add the necessary code to register history points as the
result of user events in the page such as selecting an animal or displaying its image.
a. Add code to create a history point when the selected animal of the drop down list
changes. In Solution Explorer, double-click main.js under the Scripts folder and
paste the following code inside the onDescriptionRetrieved function:
function onDescriptionRetrieved(result)
{
showDescription(result);
var selectedAnimal =
$get('AnimalSelect').options[$get('AnimalSelect').selected
Index].text;
addHistoryPoint(selectedAnimal);
}

Introduction to ASP.NET AJAX 3.5 SP1
Page 9 of 13
Tasks
Detailed Steps
b. Add code to register a history point when the image link button is clicked. To do
this, paste the following code inside the onImageRetrieved function:
{
showImage(result);
var selectedAnimal =
$get('AnimalSelect').options[$get('AnimalSelect').selected
Index].text;
addHistoryPoint(selectedAnimal + " Image");
}
c. Add code to save the history points. To do this, paste the following code inside the
addHistoryPoint function:
function addHistoryPoint(historyPointName)
{
var animalIndex = $get('AnimalSelect').selectedIndex;
var animalDescription = $get('Description').innerHTML;
var animalImage = $get("AnimalImage").src;
var pageState = { "animalIndex": animalIndex,
"animalDescription":
animalDescription,
"animalImage": animalImage
};

userNavigated = false;
Sys.Application.addHistoryPoint(pageState,
historyPointName);
userNavigated = true;
}
Note: To create a browser history point on the client side, the
Sys.Application.addHistoryPoint method of the ASP.NET AJAX library is called. This
method enables you to store key/value pairs in a JSON object (pageState) that
identifies the state of your application, along with optional data to represent the title
of the history entry in the browser. The saved data can then be used to re-create the
state of the page when a subsequent history navigation event is raised.
4. Restore the page
state
Note: When you add a history point, or when the page is navigated and contains
history state in the URL, the Sys.Application.navigate event is raised. This provides an
event in the client that notifies you that history state has changed. You can handle the
navigate event to recreate objects with state data or perform other operations.
a. Add a handler for the navigate event. To do this, paste the following code inside
the pageLoad function:
function pageLoad()
{
Sys.Application.add_navigate(onNavigate);
}
b. Implement the handler. To do this, paste the following code inside the onNavigate
function:
function onNavigate(sender, e)
{
if (userNavigated)
{
restorePage(e.get_state());
}
}
Introduction to ASP.NET AJAX 3.5 SP1
Page 10 of 13
Tasks
Detailed Steps
Note: One difference between client and server approaches is the point in the
application lifecycle when the navigate event is raised. When the
ScriptManager.AddHistoryPoint method is called, it modifies the current URL to
register the history point in the browser stack. The Navigate event is not raised until
the browser’s back or forward buttons are used.
In the client-side approach, on the other hand, the Navigate event is raised both when
Sys.Application.addHistoryPoint function is called and whenever the browser
navigation buttons are used.
To deal with this behavior you use the userNavigated global variable to ensure that
the page state is restored only when a Web page is navigated by the user. This
variable is set to false before calling the Sys.Application.addHistoryPoint function,
and is immediately reset to true after the call.
c. Add code to re-create the page based on state information. To do this, paste the
following code inside the restorePage function:
function restorePage(pageState)
{
var animalIndex = pageState.animalIndex;
var animalDescription = pageState.animalDescription;
var animalImage = pageState.animalImage;

if (animalIndex == null || animalIndex == "")
{
$get('AnimalSelect').selectedIndex = 0;
}
else
{
$get('AnimalSelect').selectedIndex = animalIndex;
}

if (animalDescription == null || animalDescription ==
"")
{
hideDescription();
}
else
{
showDescription(animalDescription);
}

if (animalImage == null || animalImage == "" ||
animalImage == "http:///")
{
hideImage();
}
else
{
showImage(animalImage);
}
}


Introduction to ASP.NET AJAX 3.5 SP1

Tasks
Detailed Steps
c.
Click on the link below the text to display the zebra’s image.
Figure


d.
Click on the browser’s back button to return to the previous state.
Figure 3

Introduction to ASP.NET AJAX 3.5 SP1

Page 12 of 13
Detailed Steps

Click on the link below the text to display the zebra’s image.

Figure
2. Display the zebra’s image.
Click on the browser’s back button to return to the previous state.
Figure 3
. Return to the previous state.
Click on the browser’s back button to return to the previous state.

Introduction to ASP.NET AJAX 3.5 SP1

Tasks
Detailed Steps

e.
Continue navigating through different anim
Pages
Figure 4
f.
Close the Browser window to end this verification.

Introduction to ASP.NET AJAX 3.5 SP1

Page 13 of 13
Detailed Steps

Continue navigating through different anim
als and their images. Press the
Pages

button to see the titles of all the history points you have visited.
Figure 4
. Browser history stack after navigating through several history points.
Close the Browser window to end this verification.

als and their images. Press the
Recent
button to see the titles of all the history points you have visited.

. Browser history stack after navigating through several history points.