47,99 €
Over 60 recipes for writing client script in ASP.NET 4.6 applications using jQuery
This book is for ASP.NET developers who want to use jQuery to write client scripts for cross-browser compatibility. The book assumes no prior knowledge of ASP.NET or jQuery, and every recipe is self-contained and explained in an easy-to-follow manner. Familiarity with Visual Studio and MS SQL Server is preferred, but not compulsory.
jQuery is a lightweight JavaScript library that has changed the landscape of client scripting in web applications. Developed by John Resig in 2006, it has taken the web by storm because of its cross-browser compatibility and the ability to get more done with less code. It has gained popularity with ASP.NET developers and is now distributed with Visual Studio and the NuGet package manager.
ASP.NET jQuery Cookbook explores the wide range of utilities that the jQuery library provides. It teaches you the nitty-gritty of plugging in these features in ASP.NET web applications. It covers every aspect of interfacing the library, right from downloading and including jQuery on web pages to selecting controls, handling events, and creating animations. This book also walks you through DOM traversal and manipulation in ASP.NET and then through visual effects and graphics in ASP.NET sites. It explores advanced features such as posting AJAX requests and writing plugins. It will provide you with all the information you need to use this library confidently with ASP.NET.
This book takes a hands-on, pragmatic approach to solving common problems in ASP.NET applications using jQuery. Every recipe has detailed steps with screen captures and code snippets. The necessary theoretical concepts are introduced as and when needed.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 376
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2011
Second edition: February 2016
Production reference: 1220216
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78217-311-3
www.packtpub.com
Author
Sonal Aneel Allana
Reviewer
Ayad Boudiab
Commissioning Editor
Dipika Gaonkar
Acquisition Editor
Divya Poojari
Content Development Editor
Priyanka Mehta
Technical Editors
Dhiraj Chandanshive
Devesh Chugh
Copy Editor
Rashmi Sawant
Project Coordinator
Izzat Contractor
Proofreader
Safis Editing
Indexer
Priya Sane
Graphics
Jason Monteiro
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
Sonal Aneel Allana works as a sessional lecturer at the Singapore campus of the University of Newcastle and the University of Hertfordshire. Her teaching areas include degree level courses in e-learning, intelligent systems, robotics, operating systems, and programming in C/C++, .NET, Java, and Android. She is keenly interested in JavaScript frameworks, such as Bootstrap, Node.js, and AngularJS. She has worked in the IT industry for over 10 years in various positions, such as an application developer, project leader, and trainer. She holds a master's degree in computing from the National University of Singapore and a bachelor's degree in computer engineering from the University of Mumbai. She is certified in security technology and computational neuroscience. She is also the author of the first edition of ASP.NET jQuery Cookbook.
I have enjoyed the journey of writing this book. The process of discovering the magic of jQuery has been enlightening and enthralling. I would like to thank my readers for their valuable feedback that I have incorporated in this edition.
This journey would not be possible without the support of my lovely family. Heartfelt thanks to everyone, especially to my parents, my husband, Aneel, and little, Abraham.
Thanks to the excellent team at Packt and to Priyanka for keeping me going. Special thanks to my reviewer, Ayad Boudiab, for his critical analysis of the material and for providing me valuable insights.
Ayad Boudiab is a senior software engineer. He has more than 17 years of experience in application development on Windows platforms. He works across multiple technologies in the .NET stack. In addition to his corporate experience, he has more than 20 years of experience in technical training and teaching. He has taught multiple courses in colleges and online. He has most recently worked with C#, JavaScript, jQuery, ASP.NET, Knockout JS, Angular JS, Kendo UI, HTML5, and SQL Server. You can contact him at <[email protected]>.
Ayad is currently a contractor for a healthcare company in Atlanta. He has reviewed many IT books and written supplements for Wiley, Pearson, nSight, Prentice Hall, among other publishers.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
jQuery is a lightweight JavaScript library that has changed the landscape of client scripting in web applications. Developed by John Resig in 2006, it has taken the Web by storm because of its cross-browser compatibility and its ability to get more done with less code. The library is supported by an active community of developers and has grown significantly over the years. Using jQuery eases many client scripting tasks, such as event handling, embedding animations, writing Ajax enabled pages, among many more, and adds to the interactive experience of the end user. Its extensible plugin architecture enables developers to build additional functionalities on top of the core library.
Learning jQuery and using it in ASP.NET applications is an indispensable skill for ASP.NET developers. This book attempts to impart this skill by exploring diverse recipes for fast and easy solutions to some of the commonly encountered problems in ASP.NET 4.6 applications.
Chapter 1, Getting Started with jQuery in ASP.NET, describes recipes to download and include jQuery in ASP.NET 4.6 Web and MVC applications. It discusses the CDN, NuGet Package Manager, as well as debugging the jQuery code in Visual Studio.
Chapter 2, Using jQuery Selectors with ASP.NET Controls, describes various jQuery selectors that can be used to manipulate ASP.NET controls. These selectors can select controls based on the ID, CSS class, HTML tag, attribute, or position in the document.
Chapter 3, Event Handling Using jQuery, describes recipes to handle different types of events, such as mouse, keyboard, and form events. It also explains event delegation and detaching of events.
Chapter 4, DOM Traversal and Manipulation in ASP.NET, describes techniques to traverse the document, such as accessing parent, child, or sibling elements. It also teaches manipulation strategies to add and remove elements at runtime.
Chapter 5, Visual Effects in ASP.NET Sites, discusses recipes to create different types of animation effects on ASP.NET controls, such as Panel, AdRotator, TreeView, Menu, and GridView. Effects such as enlarging, sliding, and fading are covered in this chapter.
Chapter 6, Working with Graphics in ASP.NET Sites, discusses recipes to work with images and explains effects, such as zooming, scrolling, and fading on images. Utilities such as image gallery, image preview, and 5-star rating control are also explored in this chapter.
Chapter 7, Ajax Using jQuery, explains how Ajax calls can be made to page methods, web services, WCF services, Web API, MVC controllers, and HTTP handlers.
Chapter 8, Creating and Using jQuery Plugins, demonstrates how plugins can be created and included in projects. It also describes how to use the Node Package Manager (NPM) and Bower to download and manage third-party plugins.
Chapter 9, Useful jQuery Recipes for ASP.NET Sites, summarizes the book with diverse recipes to solve common real-world problems. You can find this chapter at: https://www.packtpub.com/sites/default/files/downloads/4836OT_Chapter_09.pdf.
To work with the examples of this book, you will need the following:
Some recipes also require the use of third-party jQuery plugins, such as validation and cycle plugins.
This book is for ASP.NET developers who want to use jQuery to write client scripts for cross-browser compatibility. No prior knowledge of ASP.NET or jQuery is expected, and every recipe is self-contained and explained in an easy-to-follow manner. The code samples in this book are provided in both C# and VB. Familiarity with Visual Studio and MS SQL Server is preferred, but not compulsory.
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ASPNET_jQuery_Cookbook_Second_Edition_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books – maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we will cover the following recipes:
As a web developer, you often require to include functionalities in your websites that make writing a client script in JavaScript inevitable. Getting the client script to produce the same response for all browsers has always been a challenge. jQuery helps you overcome this difficulty. In essence, jQuery is a powerful JavaScript library that works across all browsers, such as Internet Explorer (IE), Firefox, Safari, Chrome, Opera, iOS, and Android. It takes away the agony that developers face in order to maintain their client scripts across different platforms.
jQuery is popular not only because of its cross-browser support, but also because it is packed with features that developers can plug and play. It has changed the way developers write a client script. In addition to reducing the amount of code that needs to be written, it provides features for traversing the DOM, event handling, building animations, and AJAX, among many more.
This chapter deals with acquiring the library and other supporting files. It aims to cover different aspects of including and using jQuery in ASP.NET 4.6 web application projects, such as web forms and MVCs.
This book is based on Visual Studio 2015 and jQuery 2.1.4. The scripts have been tested in Internet Explorer 11.0.96, Mozilla Firefox 38.0.1, and Google Chrome 47.0.2526.
If you are familiar with downloading and including jQuery in your ASP.NET applications, you can skip this chapter and move on to recipes for manipulating controls in Chapter 2, Using jQuery Selectors with ASP.NET Controls.
This recipe explains how to download jQuery on your system along with the version/build to use and the supporting files that are required.
Following are the steps to download jQuery:
jQuery is available in two different major versions at the time of writing:
Though the Application Programming Interface (API) is the same for both major versions, the difference lies in the support offered for certain browsers. The 2.x line does not support old browsers, such as IE 6, 7, and 8, while the 1.x line continues with this support. So, if the end users of your application will not be using old browsers, you can download the 2.x version.
The jQuery library consists of a single JavaScript (.js) file and can be downloaded in the following formats:
To download the file, simply right-click on the required version, 1.x or 2.x, and the required format: uncompressed or compressed. Save the file in a location of your choice as shown in the following screenshot:
Note the following naming convention for the jQuery library:
Uncompressed
Compressed
Version 1.x
jquery-1.x.x.js
jquery-1.x.x.min.js
Version 2.x
jquery-2.x.x.js
jquery-2.x.x.min.js
The compressed (minified) version is clearly distinct from the uncompressed version because of the .min.js extension. The minified file uses code optimization techniques, such as removing whitespaces and comments as well as reducing variable names to one character. This version is difficult to read, so the uncompressed version is preferred when debugging.
On the download page, there is also a map file available with the .min.map extension. Sometimes, when bugs appear in the production environment necessitating troubleshooting, the use of the minified file for debugging can be difficult. The map file simplifies this process. It maps the compressed file back to its unbuilt state so that during debugging, the experience becomes similar to using the uncompressed version.
The Understanding CDN for jQuery recipe.
A Content Delivery Network (CDN) hosts content for users through large distributed systems. The advantage of using a CDN is to improve the performance. When using a CDN to retrieve the jQuery library, if the files have been downloaded earlier, they will not be re-downloaded. This can help you improve the response time.
The following CDNs are available for jQuery files:
To include jQuery on a web page, the URL of the respective CDN can be used so that files can be directly served from the CDN instead of using the local copies. The following table summarizes the respective CDN URLs for jQuery files:
CDN
URL
jQuery's CDN
Version 2.x:
http://code.jquery.com/jquery-2.x.x.js
http://code.jquery.com/jquery-2.x.x.min.js
Version 1.x:
http://code.jquery.com/jquery-1.x.x.js
http://code.jquery.com/jquery-1.x.x.min.js
The Google CDN
Version 2.x:
https://ajax.googleapis.com/ajax/libs/jquery/2.x.x/jquery.js
https://ajax.googleapis.com/ajax/libs/jquery/2.x.x/jquery.min.js
Version 1.x:
https://ajax.googleapis.com/ajax/libs/jquery/1.x.x/jquery.js
https://ajax.googleapis.com/ajax/libs/jquery/1.x.x/jquery.min.js
The Microsoft CDN
Version 2.x:
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.min.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.min.map
Version 1.x:
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.min.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.min.map
The CDNJS CDN
Version 2.x:
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/jquery.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/jquery.min.map
Version 1.x:
https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/jquery.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/jquery.min.map
The jsDelivr CDN
Version 2.x:
https://cdn.jsdelivr.net/jquery/2.x.x/jquery.js
https://cdn.jsdelivr.net/jquery/2.x.x/jquery.min.js
https://cdn.jsdelivr.net/jquery/2.x.x/jquery.min.map
Version 1.x:
https://cdn.jsdelivr.net/jquery/1.x.x/jquery.js
https://cdn.jsdelivr.net/jquery/1.x.x/jquery.min.js
https://cdn.jsdelivr.net/jquery/1.x.x/jquery.min.map
Note that CDNs may not have the latest files when new versions of the jQuery library are launched since it usually takes a couple of days for third-parties to update their files. In the case of new releases, always check the available version before downloading them.
CDNs consist of servers situated in data centers in strategic locations across the globe. When a client requests a resource from a CDN, the server that is geographically closest to the client processes the request. These servers are also known as edge servers. In addition to this, edge servers have a caching mechanism to serve various assets. All this helps you improve the client's response time.
The Using NuGet Package Manager to download jQuery recipe
NuGet is a package manager available with Visual Studio. It simplifies the process of installing and upgrading packages. This recipe demonstrates the use of NuGet to download the jQuery library.
To launch NuGet for a particular project, go to Tools | NuGet Package Manager | Manage NuGet Packages for Solution... as shown in the following screenshot:
Alternatively, right-click on the project in the Solution Explorer tab, and select Manage NuGet Packages.
Perform the following steps to download jQuery using NuGet Manager:
Searching for packages in NuGet
If jQuery is not visible in the left-hand side panel, you need to search for it by keying in jQuery in the search box in the top left corner of the NuGet Manager screen.
The NuGet Package Manager downloads the selected version of jQuery in the Scripts folder. Any other version existing in the Scripts folder is deleted. The Scripts folder will look like the following screenshot:
The files downloaded by NuGet are as follows (the version numbers may change in the future):
The Downloading jQuery from jQuery.com recipe
To create ASP.NET 4 .6 Web Applications, Visual Studio provides various ready templates such as Empty, Web Forms, MVC, Web API, and so on. This recipe will use the Empty template, which provides the developer with an empty project structure that consists of only the web.config file.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Following are the steps to create a project by using Empty template:
Website or web project?
Instead of creating a new project, you can also create a new website. Unlike a project, a website does not contain a collective project file to track individual files in the application. To create a website, go to File | New | Web Site.... This will launch the New Website dialog box with the list of available templates. Select the ASP.NET Empty WebSite template.
In the remaining recipes, when asked to create a Web Application project using the Empty template, follow the steps listed in this section.
Following are the steps to include jQuery using script block:
For development mode, the code is as follows:
For release mode, the code is as follows:
The Downloading jQuery from jQuery.com recipe
In addition to adding jQuery to web forms using the script block and the ScriptManager control, the code-behind file can also emit the required script code. This recipe will demonstrate how this can be done.
In the Page_Load event handler of Default.aspx.vb, use the RegisterClientScriptInclude method to generate a script block on the page, as follows:
For VB, the code is as follows:
For C#, the code is as follows:
The RegisterClientScriptInclude method requires two parameters: the key and URL. It adds the script block with the path to the jQuery library in the <form> element, as shown in the following screenshot. The Page.ResolveUrl method is used to return a URL relative to the site root:
Since the jQuery library is added to the <form> element, all the jQuery code should be written in the <form> element instead of the <head> element, preferably toward the end of the page before closing the <form> element.
The Adding jQuery to an empty ASP.NET web project using a script block recipe
So far, all examples have used the Empty template for
