Tải bản đầy đủ (.pdf) (10 trang)

ASP.NET 4 Unleased - p 181 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (658.79 KB, 10 trang )

ptg
1774
points during an application’s execution. The $(document).ready() event fires when the
Domain Object Model (DOM) is loaded. Generally, you can put most of your jQuery code
in this event:
$(document).ready(function() {
// your jQuery code goes here
}
By doing so, you’re ensuring that your page is ready before it runs your code. Otherwise,
your logic might start executing before the page has completed loading, and your code
might not work as expected.
In Listing 40.2, our script tells the browser to execute the sayMessage() method when the
document is ready. When you execute the page, you can see the alert box pop up as soon
as you open the page. Although it appears to pop up right away, the browser is actually
waiting until any other page-preparing logic has completed and is ensuring that the DOM
is fully loaded. When those conditions are met, the code in $(document).ready() fires
and you see the alert box.
jQuery Selectors
Selectors are a core piece of the jQuery library. jQuery code follows this basic
methodology:
Select an element.
Do something with it.
As we mentioned above, the $() is the method that you use to select elements. For
$(document).ready(), we’re actually selecting the “document” and defining what to do
when the ready() event fires.
You can select any element (or multiple elements) on your page. Following are three basic
ways of selecting elements:
. By ID—Matches a single element with the element ID. The ID you provide should
be prefaced by a # character. For example, $(“#myId”) would match <div
id=”myId”>.
. By CSS Class—Matches all elements with the provides CSS class. The class you


provide should be prefaced with a . character. For example,
$(“.navigationListItem”) would match <li class=”navigationListItem”>.
. By Element—Matches all elements by tag name. For example, $(“div”) would
match <div id=”myId1”> and <div id=”myId2”>.
CHAPTER 40 Client-Side AJAX with jQuery
From the Library of Wow! eBook
ptg
1775
What Is jQuery?
40
After selecting an element (or elements), you need to do something with it. For example,
you can define what should execute when you click an element by using the ”click”
function. Listing 40.3 demonstrates this:
LISTING 40.3 jqueryClick.js
/// <reference path=”/Scripts/jquery-1.4.1.js”/>
function spanClicked() {
$(“#colorSpan”).addClass(“redClass”);
}
$(document).ready(function () {
$(“#clickSpan”).click(spanClicked);
});
This code has two sections of jQuery. First, we define a function called ”spanClicked” that
selects the element with the ID ”colorSpan”. It then adds a CSS class to that element
called ”redClass”Second, we define the $(document).ready() code. When the document
finishes loading, we select the element with an ID of ”clickSpan” and tell it to execute
the ”spanClicked” function whenever that element is clicked.
Notice how we use inline function()syntax in the $(document).ready code. This is called
an anonymous function in JavaScript and enables you to define functions inside of your
logic without needing to explicitly define and name it. It is often used with jQuery and
enables you to nest all your logic in a single call instead of defining a method for each

one. It dramatically improves the readability and fluidity of your code as well.
The page in Listing 40.4 defines the span elements along with the CSS class and demon-
strates the jQuery selectors.
LISTING 40.4 jqueryClick.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><script type=”text/javascript” src=”./Scripts/jquery-1.4.1.js”></script>
<script type=”text/javascript” src=”./Scripts/jqueryClick.js”></script>
<html xmlns=”
<head id=”Head1” runat=”server”>
<title></title>
From the Library of Wow! eBook
ptg
1776
<style type=”text/css”>
.redClass
{
color: Red;
}
</style>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<p><span id=”clickSpan”>This is the span that we will click.</span></p>
<p><span id=”colorSpan”>This will turn red when we click on it.</span></p>
</div>
</form>
</body>
</html>

There is an amazing amount of events and functions available in jQuery to apply to your
selected objects. For a complete list, visit the documentation and tutorial sections at
.
Calling Web Services from the Client
The heart of Ajax is the capability to send and retrieve information from the web server
without needing to post back a page to the web server. Ajax is all about performing
“sneaky” postbacks.
The vision behind a pure Ajax application is that it should consist of a single page. All
updates to the single page after it has been loaded should be performed by calling web
services. You should never need to perform a postback because any postback results in a
bad user experience. (The page jumps and the universe freezes.)
The jQuery library provides support for calling web services directly from the client (the
web browser) with a built-in function called $.ajax. In this section, you learn two
methods of exposing a web method to an AJAX page. You learn how to call a web method
from a separate web service and how to call a web method exposed by the page.
Calling an External Web Service
Let’s start simple. We create a Quotation web service that randomly returns a quotation
from a list of quotations. Next, we create an AJAX page that contains a button. When you
click the button, a random quotation displays in a <span> tag (see Figure 40.4).
CHAPTER 40 Client-Side AJAX with jQuery
From the Library of Wow! eBook
ptg
1777
Calling Web Services from the Client
40
FIGURE 40.4 Retrieving a random quotation from the server.
The first step is to create the web service, which is contained in Listing 40.5.
LISTING 40.5 QuotationService.asmx
<%@ WebService Language=”C#” Class=”QuotationService” %>
using System;

using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Collections.Generic;
[WebService(Namespace = “
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class QuotationService : System.Web.Services.WebService
{
[WebMethod]
public string GetQuote()
{
List<string> quotes = new List<string>();
quotes.Add(“The fool who is silent passes for wise.”);
quotes.Add(“The early bird catches the worm.”);
From the Library of Wow! eBook
ptg
1778
quotes.Add(“If wishes were true, shepherds would be kings.”);
Random rnd = new Random();
return quotes[rnd.Next(quotes.Count)];
}
}
You create the file in Listing 40.5 by selecting Website, Add New Item and choosing the
Web Service item.
The web service contains a single web method named GetQuote(). This method returns a
single quotation from a list of quotations as a string.
There is only one thing special about this web service. A ScriptService attribute is
applied to the web service class. (The ScriptService attribute lives in the

System.Web.Script.Services namespace.) You must add this attribute to call the web
service from an AJAX page.
Now that we have created the web service, we can call it from an AJAX page. The page in
Listing 40.6 calls the web service to display a random quotation.
LISTING 40.6 ShowWebServiceMethod.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

<html xmlns=”
<head id=”Head1” runat=”server”>
<title>Show Web Service Method</title>
<script type=”text/javascript” src=”./Scripts/jquery-1.4.1.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“#btnGet”).click(function () {
$.ajax({
type: “POST”,
dataType: “json”,
contentType: “application/json”,
url: “QuotationService.asmx/GetQuote”,
success: function (data) {
$(“#spanQuote”).html(data.d);
},
error: function () {
alert(“The call to the web service failed.”);
}
CHAPTER 40 Client-Side AJAX with jQuery
From the Library of Wow! eBook
ptg
1779

Calling Web Services from the Client
40
})
});
});
</script>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<input id=”btnGet” type=”button” value=”Get Quote” />
<br /><br />
<span id=”spanQuote”></span>
</div>
</form>
</body>
</html>
You should note several things in this page. To begin, the first thing we do in the
$(document).ready() call is add a click event handler to the ”btnGet” element. This click
event makes one function call to the $.ajax function.
The $.ajax jQuery function makes an asynchronous call to a URL. In this case, we call the
web service method that we defined at QuotationService.asmx/GetQuote. If this asynchro-
nous call is successful, the “success” parameter’s function gets called, which selects the
“spanQuote” and fills it with the data that was returned by using the “html” jQuery
function.
We also pass in a data type and content data type of “json” to our web service. JSON
stands for JavaScript Object Notation and is a lightweight format that enables you to
define an unordered set of name/value pairs. This data is contained in the ”d” property of
data—when we call the ”html” jQuery function, we pass in ”data.d” as the parameter so
all the data is pushed into the span. When web services first started being utilized, XML

was used almost exclusively to send data back and forth. Today, JSON is quickly becoming
the standard because large amounts of data can be sent back and forth without the extra
overhead of XML.
When you call a web method with $.ajax, you can pass a reference to both a success and
an error method. If the web method call is successful, the success method is called.
Otherwise, the error method is called.
In Listing 40.6, if the $.ajax call is successful, the quotation displays in a <span> tag in
the body of the page.
From the Library of Wow! eBook
ptg
1780
CHAPTER 40 Client-Side AJAX with jQuery
Calling a Static Page Method
If you do not plan to call a web method from multiple pages, don’t perform all the work
of creating a separate web service. Instead, you can expose a static method from the same
AJAX page calling the web method.
For example, the page in Listing 40.7 includes a server method named GetQuote().
LISTING 40.7 ShowPageMethod.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><script runat=”server”>
[System.Web.Services.WebMethod]
public static string GetQuote()
{
List<string> quotes = new List<string>();
quotes.Add(“The fool who is silent passes for wise.”);
quotes.Add(“The early bird catches the worm.”);
quotes.Add(“If wishes were true, shepherds would be kings.”);
Random rnd = new Random();
return quotes[rnd.Next(quotes.Count)];

}
</script>
<html xmlns=”
<head id=”Head1” runat=”server”>
<title>Show Web Service Method</title>
<script type=”text/javascript” src=”./Scripts/jquery-1.4.1.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“#btnGet”).click(function () {
$.ajax({
type: “POST”,
dataType: “json”,
contentType: “application/json”,
url: “ShowPageMethod.aspx/GetQuote”,
success: function (data) {
$(“#spanQuote”).html(data.d);
},
error: function () {
alert(“The call to the web service failed.”);
}
From the Library of Wow! eBook
ptg
1781
Summary
40
})
});
});
</script>
</head>

<body>
<form id=”form1” runat=”server”>
<div>
<input id=”btnGet” type=”button” value=”Get Quote” />
<br /><br />
<span id=”spanQuote”></span>
</div>
</form>
</body>
</html>
Just like in the previous section, you can call a page method in the exact same manner as
a web service. We pass in the URL and method name of our GetQuote() method to the
$.ajax call, and our success and error references do the rest. This is handy when you
develop page-specific functionality that doesn’t require the extra work of building a sepa-
rate web service.
Summary
In the first part of this chapter, you learned about the jQuery library and what it has to
offer. You learned about the $(document).ready() event and how to select elements with
the $() jQuery function.
In the next part, you learned how to call web services from the browser. You learned how
to call a web method in an external web service and a static web method exposed from a
server-side page.
jQuery is a powerful tool that makes it incredibly easy to add client-based functionality to
your web applications with little code. We have barely scratched the surface of what
jQuery can do—it is a great way to improve the user experience of your applications, so
spend some time to learn everything it has to offer.
From the Library of Wow! eBook
ptg
This page intentionally left blank
From the Library of Wow! eBook

ptg
Index
Symbols
$.ajax call, 1779
@Director parameter, 512
$(document).ready( ) method, jQuery,
1773-1774
/ (forward slash), 1124
$get( ) method, 1754
@Id parameter, 512
$( ) method, jQuery, 1773-1774
%@ OutputCache % directive, 1337, 1369
CacheProfile attribute, 1361
Location attribute, 1349, 1351
VaryByControl attribute, 1342, 1344
VaryByCustom attribute, 1346-1349
VaryByHeader attribute, 1345-1346
VaryByParam attribute, 1338, 1342
~ (tilde character), 1124
@Title parameter, 512
_ (underscore character), 730
A
a templates, PagerTemplate, 509
Abandon( ) method, 1284-1285
About.asax file, 1092-1093
absolute cache expiration policy, 1376-1377
absolute expiration policy, Data Caching,
1390-1392
absolute layouts, 288-290
Absolute.css file, 288-290

From the Library of Wow! eBook

×