Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 322 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
322
Dung lượng
10,25 MB
Nội dung
Joshi Shelve in .NET User level: Beginning–Intermediate www.apress.com SOURCE CODE ONLINE BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® Beginning jQuery 2 for ASP.NET Developers By combining jQuery with ASP.NET you get the best of both worlds: the client-side interactivity and responsiveness of JavaScript with the robustness and extensibility of Microsoft’s web stack. Beginning jQuery 2 for ASP.NET Developers shows you how. To begin with, you’ll find out how jQuery hooks up with your ASP.NET controls, and simplifies event handling by keeping it in the browser. Then you’ll learn to handle dynamic content by interacting with the DOM. Effects and animations are one of the most popular uses of the jQuery library, so we cover that next—showing you how to get a sleek modern look and feel to your site using some of the vast library of JavaScript that’s already out there waiting to be used. Ajax is one of the areas where jQuery really shines, so you’ll find out how to make Ajax calls to web services and APIs, to get data onto a page without waiting for slow ASP.NET postbacks every time. And no book on jQuery would be complete without a first look at jQuery Mobile, to get you started building sites that work on all the major mobile platforms. What You’ll Learn: • How to select DOM elements using powerful jQuery selectors • Use jQuery with ASP.NET server controls, ASP.NET MVC form fields and other DOM elements • Manipulate and traverse the DOM tree and add jQuery effects to ASP.NET web pages • Learn to make Ajax calls and pass JSON data to Web Services, Page Methods, WCF services, controller action methods, HTTP handlers and Web APIs • Understand code reuse by creating and using jQuery plugins • Get introduced to jQuery UI and jQuery mobile and use them in ASP.NET Web Forms and MVC applications RELATED 2630437814309 ISBN 978-1-4302-6304-3 54499 www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info v Contents at a Glance About the Author ���������������������������������������������������������������������������������������������������������������� xv About the Technical Reviewer ������������������������������������������������������������������������������������������ xvii Acknowledgments �������������������������������������������������������������������������������������������������������������xix Introduction ����������������������������������������������������������������������������������������������������������������������� xxi Chapter 1: The JavaScript You Need to Know ■ �������������������������������������������������������������������1 Chapter 2: A First Look at jQuery ■ ������������������������������������������������������������������������������������33 Chapter 3: ASP�NET Controls and jQuery Selectors ■ ����������������������������������������������������������63 Chapter 4: Event Handling ■ ���������������������������������������������������������������������������������������������103 Chapter 5: DOM Manipulation and Dynamic Content ■ �����������������������������������������������������135 Chapter 6: Traversal and Other Useful Methods ■ ������������������������������������������������������������157 Chapter 7: Effects and Animations ■ ��������������������������������������������������������������������������������179 Chapter 8: Ajax Techniques ■ �������������������������������������������������������������������������������������������193 Chapter 9: Creating and Using Plugins ■ ��������������������������������������������������������������������������231 Chapter 10: jQuery UI and jQuery Mobile ■ ����������������������������������������������������������������������255 Chapter 11: Useful jQuery Recipes for ASP�NET Applications ■ ����������������������������������������281 Appendix: Learning Resources ■ ��������������������������������������������������������������������������������������301 Index ���������������������������������������������������������������������������������������������������������������������������������303 www.it-ebooks.info xxi Introduction Welcome to the exciting world of jQuery! If you’re an ASP.NET developer looking to turbocharge your ASP.NET applications with jQuery, you picked the right book. Modern web applications leverage browsers’ resources through client-side scripting. Although JavaScript is a de facto standard as far as client-side scripting is concerned, there are several libraries built on top of JavaScript that help developers accomplish their job quickly and easily. jQuery is one of the most popular JavaScript libraries available today. If you want to develop Ajax-driven, dynamic, and cross-browser web applications using ASP.NET, understanding jQuery is an invaluable skill. While using jQuery in ASP.NET Web Forms and ASP.NET MVC projects, you need to combine the power of jQuery with server controls, controllers, services, and APIs. It is crucial to understand how jQuery can be used eectively in combination with ASP.NET features and technologies. To that end, this book teaches you how to harness the power of the jQuery library in your ASP.NET Web Forms and MVC applications. It helps you understand the foundations of jQuery from the perspective of an ASP.NET developer in a clear, step-by-step way, so that you can quickly ensure you have this invaluable skill under your belt. Who This Book Is For is book is for ASP.NET web developers who want to tap the power of jQuery in their existing or new web applications. is book doesn’t teach you ASP.NET features. I assume that you’re already comfortable working with ASP.NET and doing web application development in general. All the code samples discussed in this book use C# as the server-side programming language, so you should also know C#. Although no prior knowledge of jQuery is expected, I assume that you’re familiar with the basics of JavaScript. e examples illustrated throughout the book use SQL Server and Entity Framework. Although you need not have a detailed understanding of these technologies, you should at least be familiar with them. e book uses Visual Studio as the development tool. You should know how to work with Visual Studio to perform basic tasks such as creating projects and debugging code. Software Required To work through the examples in this book, you need the following software: Visual Studio 2013• SQL Server 2012• jQuery, jQuery UI, and jQuery Mobile library les• Web browsers: Internet Explorer 9+, Firefox, Chrome, Opera, and Safari• Although I used Visual Studio Ultimate 2013 to develop the book’s examples, most of the examples can also be developed using Visual Studio Express 2013 for Web. www.it-ebooks.info ■ IntroduCtIon xxii All the data-driven examples were developed using SQL Server 2012 Express Edition. I use the Northwind sample database in many examples, and I suggest you install it. You can download the Northwind database and its script from the MSDN downloads web site. I used jQuery 2.0.3 to write the examples presented in this book. You should consider downloading the latest versions of jQuery, jQuery UI, and jQuery Mobile from their ocial web sites. It’s always a good idea to test the client scripts you write in all the major browsers. So you might consider installing the latest versions of Internet Explorer, Firefox, Chrome, Opera, and Safari. How This Book Is Structured is book is organized into 11 chapters and one appendix. Here’s a quick overview: Chapter 1• gives you a quick recap of JavaScript programming. You can brush up on your JavaScript skills before taking on jQuery. Chapter 2• gives you a peek into jQuery. You learn the basics, such as downloading and installing jQuery on your machine. You also develop a simple application in ASP.NET Web Forms and MVC. Chapter 3• gives you a detailed understanding of jQuery selectors. You learn to match DOM elements using powerful and exible selectors. is chapter also details techniques to deal with server controls while selecting them in the jQuery code. Chapter 4• teaches you one of the most commonly used features: event handling. It covers commonly used events such as window, keyboard, and mouse events. Some advanced concepts relating to event handling, such as passing custom data to the event handler, are also covered. Chapter 5• is about DOM manipulation using jQuery. Topics covered include applying CSS styles, working with attributes, and manipulating DOM elements. Chapter 6• covers DOM navigation and ltering techniques, including tree traversal, iterating, searching, working with custom data attributes, and more. Chapter 7• teaches you how to apply jQuery eects and animations to Web Form controls and page elements. You learn to apply fancy eects such as fade-in, fade-out, slide-up and slide-down. You also learn to apply custom animation eects to page elements. Chapter 8• covers an important topic: Ajax techniques oered by jQuery. is chapter discusses how ASMX web services, WCF services, MVC action methods, and the Web API can be called from the jQuery code. It also discusses the JSON format and its use in Ajax communication. Chapter 9• discusses plugins—a technique to extend the jQuery core. You can develop plugins to enhance and extend the core functionality oered by jQuery. e chapter discusses the steps involved in building a plugin and gives you some recommendations to be followed during the process. Chapter 10• gives you an overview of jQuery UI and jQuery Mobile. jQuery UI provides various widgets that you can add to ASP.NET web applications to provide professional user interface elements such as dialogs, menus, accordions, and sliders. jQuery Mobile helps you develop web applications targeted at mobile devices. Chapter 11• presents a few recipes that you will nd useful in real-world applications. e recipes covered include implementing Ajax-based paging, client-side sorting, le upload, autocomplete text box, and cascading drop-down lists. e Appendix lists some jQuery learning resources.• www.it-ebooks.info ■ IntroduCtIon xxiii Downloading the Source Code e complete source code for the book is available for download at the book’s companion web site. Visit http://www.apress.com and go to the book’s information page at http://www.apress.com/9781430263043. You can then download the source code from the Source Code/Downloads section. Contacting the Author You can reach me via my web site: http://www.binaryintellect.net. You can also follow me on popular social-networking web sites such as Facebook and Twitter (visit my web site for details). www.it-ebooks.info 1 Chapter 1 The JavaScript You Need to Know JavaScript is a programming language that adds interactivity and dynamic content to otherwise static HTML pages. Behind most fancy frills such as mouseover effects, animations, drop-down menus, and form validations, you will usually find JavaScript being used in some way or another. jQuery is a JavaScript library that simplifies your client-side programming tasks and uses the same programming constructs as JavaScript for variables, branching, and looping. While writing jQuery code, you often need to use these JavaScript programming constructs. Therefore, before you delve into jQuery programming, you must refresh your JavaScript skills. This chapter is intended to give you a quick overview of commonly used JavaScript features so that you can use the knowledge gained in this chapter in the remainder of the book. If you are already familiar with JavaScript, you can skip this chapter, or glance over its content and jump to the next chapter. Specifically, you will learn how to do the following: Understand basic programming constructs used in JavaScript for branching and looping• Work with JavaScript variables and data types • Use built-in string, number, and date functions• Create and use your own functions• Note ■ Although this chapter is intended to give you an overview of the JavaScript language, it does not cover all JavaScript features. For more information on JavaScript programming, see https://developer.mozilla.org/en-US/docs/Web/JavaScript. Your First JavaScript Program In this section, you will develop a simple ASP.NET Web Form that makes use of JavaScript to seek a confirmation from the end user. Although the application is not very sophisticated, it does throw light on some basics of JavaScript. Figure 1-1 shows the Web Form you will develop. www.it-ebooks.info CHAPTER 1 ■ THE JAVASCRIPT YOU NEED TO KNOW 2 As shown in Figure 1-1, the Web Form consists of a couple of Label controls, a TextBox, and a Button server control. Once you enter a name and hit the Submit button, a confirmation dialog is shown that seeks your consent to submit the form. Depending on your choice, either the form submission is canceled or the form is submitted to the server. Upon postback, the entered name is displayed in a Label control. To begin developing this application, create a new ASP.NET Web Application based on the Empty project template using Visual Studio (see Figure 1-2). Figure 1-1. Your first JavaScript program Figure 1-2. Creating a new ASP.NET Empty Web Application using Visual Studio www.it-ebooks.info CHAPTER 1 ■ THE JAVASCRIPT YOU NEED TO KNOW 3 Add a new Web Form to the project and name it FirstJS.aspx. Design the Web Form as shown in Figure 1-1 by dragging and dropping the respective server controls from the toolbox. The HTML and server control markup of the Web Form is shown in Listing 1-1. Listing 1-1. Markup of FirstJS.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FirstJS.aspx.cs" Inherits="Chapter_01. FirstJS" %> <body> <form id="form1" runat="server"> <h1>First JavaScript Program</h1> <asp:Label ID="Label1" runat="server" Text="Enter your name :"></asp:Label> <br /> <br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" /> <br /><br /> <asp:Label ID="Label2" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label> </form> </body> </html> The markup contains two Label controls: one that acts as the prompt for the name text box, and the other that is placed below the Submit button. The server-side click event handler of Button1 simply outputs the name entered by the user in Label2. Listing 1-2 shows this event handler. Listing 1-2. Submit Button Server-Side Click Event Handler protected void Button1_Click(object sender, EventArgs e) { Label2.Text = "Hello " + TextBox1.Text; } So far, the application doesn’t use any JavaScript. In the next step, you add some JavaScript code that is invoked when the user clicks the Submit button. To do so, modify the markup of the Submit button as shown here: <asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return confirmName();" /> You can add the OnClientClick attribute in two ways: you can either switch to the source view of Visual Studio IDE and key in the markup shown in bold letters, or set the OnClientClick property of Button1 in the Properties window. The OnClientClick property is used to specify the client-side (JavaScript) code that is to be executed when the button is clicked. In this case, you set the OnClientClick property to return confirmName(). confirmName() is a custom JavaScript function that you will write next. Go into the <head> section of the Web Form and add a <script> block, as shown in Listing 1-3. www.it-ebooks.info CHAPTER 1 ■ THE JAVASCRIPT YOU NEED TO KNOW 4 Listing 1-3. confirmName() Function <script type="text/javascript"> function confirmName() { var textbox = document.getElementById("TextBox1"); var flag = window.confirm("You entered : " + textbox.value + "\n\nDo you wish to continue?"); if (flag) { return true; } else { return false; } } </script> The <script> block shown in Listing 1-3 contains a custom JavaScript function named confirmName(). The confirmName() function is intended to seek confirmation from the end user and accordingly cancel or continue with the form submission. First, it grabs a reference to the text box using the getElementById() method of the document object. The document object represents the current web page loaded in the browser window. The getElementById() method accepts an ID of an HTML element and returns a Document Object Model (DOM) object representing the element. The return object is stored in a JavaScript variable named textbox. Notice the use of the var keyword to declare a variable. Note ■ The Document Object Model, or DOM, is a tree structure of the entire HTML page loaded in the browser window. Each HTML element from the page has a corresponding object in the DOM tree that can be used to manipulate the underlying HTML element. The next line declares a JavaScript variable named flag to store the return value of a built-in function: window.confirm(). The confirm() function belongs to the window object and allows you to display a dialog to the user with a developer-defined message. The dialog has OK and Cancel buttons. If the user selects OK, confirm() returns a Boolean value of true; otherwise, it returns false. The window object represents the container of the document being displayed (the browser window or a tab in which the page is loaded). In this example, you display the name entered by the user. Notice the use of the escape sequence \n\n in the message string to add new lines in the message. The value property of the text box DOM element returns the text entered in the text box. An if-else block checks the flag variable. If flag is true, the if block returns true; otherwise, the else block returns false. Depending on the value returned by the confirmName() function, the form is submitted (true) or the form submission is canceled (false). Note ■ Although confirm() is a method of the window object, in most of the browsers you can simply call it as if it were a stand-alone function. So, window.confirm() and confirm() mean the same thing in your JavaScript code. Refer to Figure 1-1 again. Can you see the timestamp printed in the footer of the Web Form? That’s the job of another <script> block that you place just above the </body> (the end body tag). Listing 1-4 shows this <script> block. www.it-ebooks.info [...]... represents April 15, 20 13 On the same lines, hours take values between 0 and 23 , minutes between 0 and 59, and seconds between 0 and 59 Thus, the third Date object represents February 20 , 20 13 at 10 :29 :00 a.m Table 1 -2 lists some of the most commonly used Date object methods Table 1 -2. Date Object Methods Method Description getFullYear() Returns a full year from a Date object (e.g., 20 13) setFullYear(val)... = document.getElementById("TextBox1").value; var val2 = document.getElementById("TextBox2").value; alert(val1 + val2); The first two lines of the code grab values entered in two text boxes—TextBox1 and TextBox2—and store them in variables val1 and val2 respectively The alert() outputs the addition of val1 and val2 If you enter numbers, say 10 and 20 , into the text boxes, you probably expect the alert()... the new date is outputted as Sat Apr 10 20 10 Many times you need to convert a string into a Date object For example, you might accept a date from the end user in dd-MM-yyyy format and then want to convert it into a Date object for further processing Here’s a simple way to do this: var str = "30/ 12/ 2013"; var dtArray = str.split("/"); var dt = new Date(dtArray [2] ,dtArray[1]-1,dtArray[0]); alert(dt.toDateString());... you to access various parts of a date such as year, month, day, and hour You can create Date objects in several ways, as shown here: var dt1 = new Date(); var dt2 = new Date (20 13, 3, 15); var dt3 = new Date (20 13, 1, 20 , 10, 29 , 0, 0); 20 www.it-ebooks.info Chapter 1 ■ The JavaScript You Need to Know The first line creates a Date object that represents the current date and time You can create a Date... is specified in the text box At the bottom of the Web Form is a Label control that displays the total number of elements in the array at a given point in time Listing 1-6 shows the relevant markup from the Web Form Listing 1-6. Markup of Web Form Dealing with Arrays . in .NET User level: Beginning Intermediate www.apress.com SOURCE CODE ONLINE BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® Beginning jQuery 2 for ASP. NET Developers By combining jQuery with ASP. NET. extensibility of Microsoft’s web stack. Beginning jQuery 2 for ASP. NET Developers shows you how. To begin with, you’ll find out how jQuery hooks up with your ASP. NET controls, and simplifies event. applications using ASP. NET, understanding jQuery is an invaluable skill. While using jQuery in ASP. NET Web Forms and ASP. NET MVC projects, you need to combine the power of jQuery with server