• .NET Developer Tools DevTools

    UI controls for ASP.NET AJAX, MVC, WPF,
    Silverlight, Windows 8 and Windows Phone

  • Hybrid Mobile Development Icenium

    Cross-platform Mobile Development Tool
    with cloud-based architecture

  • HTML5 / JavaScript Development Kendo UI

    Everything you need to build sites and
    mobile apps with JavaScript and HTML5

  • Testing Tools TestStudio

    One easy tool for Functional, Performance,
    Load and Mobile software testing

  • Web Presence Platform Sitefinity CMS

    Everything for your online business - content
    management, ecommerce, emarketing

  • Agile Project Management TeamPulse

    Simple and intuitive project management
    and collaboration software

Contact us

We are here for you.
  • usa+1‒888‒365‒2779
  • uk+44‒20‒7291‒0580
  • bg+359‒2‒8099850
  • de+49‒89‒2441642‒70
  • au+61‒2‒8090‒1465
  • emailsales@telerik.com
Your account Access to your products, updates and support
Telerik Product Families
  • Your Account
    Your Account
    Log in
  • ABOUT US

    About Telerik

    • Company
    • Press Center
    • Customers
    • Community
    • Careers
    • Contacts
Kendo UI - The way of HTML5
Products ▼
Kendo UI Web Kendo UI Mobile Kendo UI DataViz Server Side Wrappers
Demos Purchase Download
Blogs Documentation
Support ▼
Premium Forums StackOverflow Forums
Resources ▼

Featured Resource

Kendo UI Dojo


Blogs Code Library Demos Documentation FAQ Testing
Premium Forums Roadmap User Voice Videos Webinars More Resources
Contact Us Search
 

Blogs

Hello jQuery

Thursday, May 03, 2012 by Kendo UI Team Blog | Comments 14

This is the first section in the ongoing course HTML5 Development For ASP.NET Developers.

This module will covers the very basic information that you will need to know about jQuery and how to use it inside of Visual Studio / Internet Explorer. There are some good tips on things you can do with the IE Developer Tools here as well. Check out the screencast, or skip to the written summary below.

Screencast

Written Summary

In this tutorial, you will be building a sample application which takes in a user’s first name and last name, and then returns a greeting. First you will build the application in typical WebForms fashion, then you will refactor the application to use jQuery.

Create The Sample Application

Open Visual Studio. All of these examples will use Visual Studio 2010 and .NET Version 4.0, but remember that the only limiting factor to your HTML5 development is the browser. As long the browser is capable, .NET is capable.

Select File / New Project and select the ASP.NET Web Application project template.  Name the application “HellojQuery”.

file-new-project

Open the Default.aspx page.  Switch to Design view and delete all the content.  From the toolbox, drag out two TextBoxes, a Button and a Label control.  In front of the first TextBox, type “First Name: “.  After the first TextBox, put a space and then type “Last Name “.  Put a space between the second TextBox and the Button.  Put the label on the following line by pressing “Enter”.

Name the first TextBox “txtFirstName”, the second one “txtLastName”.  Name the Button “btnSayHello” and change it’s Text property to “Say Hello”.  Set the Label ID to lblResult and clear out the Text property.

default-design-view

Double-click the Say Hello button to create a new button click event in the Default.aspx.cs file.  Set the label text equal to the string “Hello “ concatenated with the Text property of txtFirstName and the Text property of txtLastName.

btnSayHello Click Event

        
protected void btnSayHello_Click(object sender, EventArgs e) {
	lblResult.Text = "Hello " + txtFirstName.Text + " " + txtLastName.Text;
}

 

Using IE Developer Tools

Press F5 or the run icon and run the application.  Don’t enter in your name yet or click the button.  Instead, press F12 to open the IE Developer Tools.  Switch to the Network tab and click the Start Capturing button.

f12-developer-tools

Refresh the page.  Notice that the Network tab now shows three items.  The first is the Default.aspx page that you are looking at.  The second is the CSS file that is referenced in the head of the Default.aspx page.  The last one is the WebResource.axd file which contains JavaScript and other resources for the page as determined by WebForms per the ASP.NET controls that you choose to use.

Also notice that the method for all three requests is a GET.  This means that the browser requested three files from the server and did that with an HTTP GET.  A GET  is commonly used when requesting information from a server.  By default when you visit a URL, your browser will do a GET to retrieve the requested site.

network-traffic-get

Now fill the form out in the application with your first name and click the Say Hello button.  The server responds as expected by setting the label text equal to the first name field plus the last name field.  Have another look at the network traffic pane.  It looks nearly identical, but the Default.aspx page was retrieved this time with a POST.  This is because this time the browser sent some data to the server – specifically the values of the first name and last name textboxes.  When browsers send information to the server and expect a response, this is typically done with a POST. 

network-traffic-post

In ASP.NET WebForms, the page posts back to itself, or the same URL. To inspect the information that was sent to the server, double click on the POST method and click on the Request Body tab. 

network-request-body

Here you can see that the _VIEWSTATE object was sent back to the server.  If you scroll down far enough, you will find the values of the first and last name textboxes in the view state object.  What happened is that the browser did a POST to the server requesting the page, but also passing in the values of the textboxes.  The server event was fired, the HTML in the Default.aspx page was altered and then sent to the browser.

This requires a complete “round trip” to the server.  This means that the browser has to load up the page all over again.  This is completely unnecessary (especially in this simple application). 

jQuery is a simple JavaScript library that allows the developer to interact with the HTML of the page (amongst many other things) in a very straight forward way. 

Add jQuery To The Project

Visual Studio projects actually come with jQuery in the Scripts folder by default.  However, these jQuery and VSDoc files may be out of date and not connected with a Nuget installation.  Delete the jQuery files in the Scripts folder, including the VSDoc file.

To install jQuery from Nuget, right-click the project and select Add Library Package Reference.  Select Online from the left-hand side and enter “jquery” in the search box.  Click the Install button on the jQuery package.  This will install the VSDoc files as well.  There is no need to install them separately.

nuget-jquery-search

This will put the latest version of jQuery in the Scripts folder.  There will be 3 files there.

1. jquery-1.7.2.js – This is the full jQuery source file.

2. jquery-1.7.2.min.js – This is the minified version of jQuery, which removes all whitespace and comments, as well as “minifying” the script to make it as small as possible.  This version is identical to the first one in every way except that it is unreadable for debugging.  This is generally the file used when an application is in production.  For development, use the full jQuery version.

3. jquery-1.7.2-vsdoc.js – This file provides Intellisense inside of Visual Studio for jQuery.  As long as this file is named in the same way as the jQuery file, Intellisense will work.

Open up the Site.Master page.  Drag the full jQuery source into the head of the page, directly below the link tag to Site.css.  This will create a new link tag pointing to the jQuery-1.7.2.js file.  JQuery has now been added to the project.

jquery-added-to-master

Using jQuery Directly In The Browser

Run the application again.  When it comes up, open the developer tools by selecting F12.  Switch to the Console tab in the developer tools.  The console allows a developer to execute arbitrary JavaScript commands at runtime.  As a test, type alert(“Hello!”); in the console and press enter. 

alert-hello

jQuery code can be executed either by calling methods off of the jQuery object, or simply using the $.  The $ is commonly known and recognized as representing jQuery. 

For this project, you should be aware of one important thing that jQuery does, and that’s select items out of the DOM.  The DOM is the Document Object Model, but you can think of this as just your page.  jQuery allows you to select elements out of your page and get or set different properties on the elements.  jQuery has many types of selectors, but it’s important to be very comfortable with the following two basic types of selectors.

1. ID Selectors

This is when you select an element based upon it’s unique ID.  Every HTML element on your page should have a unique ID.  This is done by using a # sign.

Selecting An Element By ID With jQuery

// gets the firstname textbox
var txtFirstName = $("#txtFirstName"); 

 

2. Class Selectors

This is when an element, or a group of elements is selected by the css class.  If you have several elements on a page with the same class, all of them will be returned.  This is done by using a “.” .

Selecting Elements By Class With jQuery

// gets the textboxes with a class of "textbox"
var textboxes = $(".textbox"); 

 

Enter a first and last name in the textboxes in the application before proceeding.

To select the First Name textbox value in this project, remember that you set the ID earlier in this tutorial to txtFirstName.  You then need to call the jQuery val() method to retrieve the text inside of the textbox.  Enter the following command in the console and press enter.

Get The Text Of txtFirstName

// gets the text of the element with the id txtFirstName
$("#txtFirstName").val(); 

 

Notice that the command is echoed out into the Console, but there is no value.  This mistake was made to demonstrate an important feature of ASP.NET WebForms.

txtfirstname-no-value

To debug why this didn’t work, click on the white arrow which is the element selector.  Then go up into the page and click on the textbox that you named txtFirstName.  The HTML tab will open and the element in the page will be highlighted.  Notice that it’s ID is not txtFirstName, but rather MainContent_txtFirstName.  This is because the controls were added to a content container in Default.aspx.  In ASP.NET WebForms, controls added to a parent server control will be prefixed with the parent name.  If parents are nested within parents, they may have multiple values appended onto the front.  This is to make sure that ID’s do in fact remain unique.

main-content-txt-firstname

Switch back to the Console tab and keeping in mind the actual ID of txtFirstName at runtime, enter the following command in the console.

Get The Text Of txtFirstName

// gets the text of the element with the id txtFirstName
$("#MainContent_txtFirstName").val(); 

 

Notice that the text value of the first name textbox is returned.

txtfirstname-has-value

Refactor The Application To Use jQuery

Given the fact that you can select any element in the page, and get or set its value, switch back to Visual Studio and open up the Default.aspx file.  Right above the closing </asp:Content> tag, open a new script block.  You do not have to specify the type of the script block.  All script blocks are assumed to be JavaScript unless otherwise specified.

Open A New Script Block

<script>

    // ... JavaScript will go here

</script>

 

Document Ready

Another important concept to understand in jQuery is the Document Ready function.  This is a function that jQuery will execute when the page has finished loading.  This is important as you don’t want to execute any code until all libraries, CSS and HTML elements have been loaded into the page.

The shorthand for this function is to declare a function, wrap that function in parenthesis and put the jQuery $ at the front.  This should be committed to memory as it is used quite frequently in jQuery powered applications.

Create A Document Ready Function

<script>

    $(function() {
		
	// no code here will be executed until the page has
	// finished loading
	
    });

</script>

 

Before writing any code in the document ready function, a slight modification is needed in the HTML.  All the contents inside of Default.aspx are ultimately rendered inside a Form tag that is in the Master page.  This means that any button click will cause the page to “post back” or rather, submits the page to the server.  This is the round trip that we are attempting eliminate.  Remove the Button markup and replace it with plain HTML that renders an input with a type of button.  This will display a button, but its click will not cause the form to post.

Replace ASP Button Control With Standard Input

<!-- Replace This -->
<asp:Button ID="btnSayHello" runat="server" onclick="btnSayHello_Click" 
	Text="Say Hello" />

<!-- With This -->
<input type="button" id="btnSayHello" value="Say Hello" />

 

In order to create a new click event for the input button, select the button with jQuery and then specify its click event.  When the click event is specified, a function is passed in that will be executed when the button click actually occurs.  Notice that it is unnecessary to prefix the new button with MainContent, because while it is in fact in an ASP.NET Content Area, it is not a server control and consequently its ID will not be modified at runtime.

Create A Click Event For The New Button

<script>

    $(function() {
		
	$("#btnSayHello").click(function() {
		
	    // all code here will be executed when 
	    // btnSayHello is clicked
			
	});
		
	
    });

</script>

 

Select both the first name and last name textboxes and store their values in variables.  Lastly, the lblResult control renders as a <span>  tag at runtime.  In order to set the text that’s rendered inside of the span tag, select the lblResult control with jQuery and set its html property.

The Full Click Event Code

<script>

    $(function() {
		
	$("#btnSayHello").click(function() {
		
	    // get the values of the first and last name textboxes
	    var firstName = $("#MainContent_txtFirstName").val();
	    var lastName = $("#MainContent_txtLastName").val();
			
	    // set the text of the label
	    $("#MainContent_lblResult").html("Hello " + firstName + " " + lastName);
			
	});
		
	
    });

</script>

 

Run the application.  Enter in a first name and last name value.  Click the button and notice that the value of the label is updated, but the page never posts back to the server.  All manipulation happens client side.

Further Reading / Resources

If you wish to become very knowledgeable about jQuery, it is highly recommended that you go through the “30 Days To Learn jQuery” course on TutsPlus.  After finishing this set of learning screencasts for jQuery, you should not only be extremely comfortable with the library, but you will have vastly accelerated your skills in overall HTML5 development.

Code from this module can be downloaded from the course GitHub repository.

About the Author
Burke Holland is a web developer living in Nashville, TN. He enjoys working with and meeting developers who are building mobile apps with jQuery / HTML5 and loves to hack on social API's. Burke works for Telerik as a Developer Evangelist focusing on Kendo UI. Burke is @burkeholland on Twitter.

14 Comments

  1. 1 Steve 03 May 2012
    "Every HTML element on your page should have a unique ID"

    Every important element you want to manipulate anyway, but every element would be bloaty no?
  2. 2 Burke 03 May 2012
    @Steve

    Good point!  I suppose I should have been more clear on that.  Every element that you will need to reference is accurate.
  3. 3 Ben Hayat 03 May 2012
    Burk, you're a good communicator with clear direction when talking, rather jumping all over and frustrating the viewer. :-)

    Subscribed!
    ..Ben
  4. 4 Stacy 06 May 2012
    Wow, I wish all tech posts were as clear as this. Fantastic communication skills on display here.

    Thanks!
  5. 5 Burke 07 May 2012
    @Stacy and @Ben

    Thank you so much for the kind words and I hope that I can continue to keep things simple and clear as the content gets more complex.
  6. 6 Chris Dixon 10 May 2012
    It's also worth mentioning that you can still use your own ID with .NET elements by using ClientID="Static" in the control.

    And it's standard practice (as of 1.7.1) to use the .on event for .click commands as this incorporates the jQuery live events and won't mess up within UpdatePanels (boo, hiss, but people still use them), whereas .click will do.
  7. 7 Burke 10 May 2012
    @Chris

    Good point.  And I meant to update the post with the reference to static id's as a friend mentioned that I should include it.

    As for the click event, that's also great info.  For anyone wondering, I would highly recommend reading Elijah Manor's post on using bind(), live() ,delegate() or on() instead.
  8. 8 Chris Dixon 11 May 2012
    That's a good read! It's respectful to see these posts here as they're giving people a good dive into doing things the client-side way, which is a big shift for some and a definite requisite for Kendo UI.

    As a personal suggestion, I'd potentially separate these posts out into a Tutorial section? I can imagine so many of these posts are missed as people will misunderstand Blogs as just personal posts - me being one of them!
  9. 9 Burke 11 May 2012
    @Chris

    That's a great idea and that's exactly what I plan to do when this series is finished.  These posts are written in a tutorial style so that they can be easily compiled into a neat tutorials section at the end of this course.

    Thanks for the feedback!
  10. 10 Luann 11 May 2012
    Thank you, I've recently been looking for information about this subject for a long time and yours is the best I have came upon so far. However, what about the bottom line? Are you sure in regards to the supply?
  11. 11 William 10 Jun 2012
    Hi Burke:

    Thank you for such a valuable and useful video.  Having the written summary as well makes it a reference point when we need to go back and check an item or two.

    Please keep up the good work and you bet I shall be spreading the gospel of KendoUI!

    Cheers!

    William
  12. 12 Simon 21 Jun 2012
    Hello Burke

    Just want to add that this tutorial reminds me of the articles I used to write many many moons ago and thank you for the detail and effort you have put into it.

    Regards,
    Simon
  13. 13 Michael Aebi 15 Oct 2012
    Hi Thanks for your work here.

    I have had trouble with the 

    Open A New Script Block

    I didn't know which </asp:Content> you mean. Header or Body. And i thougth always i have to put all Scripts in to the Header section.

    Finaly i found the solution in the repository. ;) 

    Just my 5 cents.


  14. 14 wp designer 02 Nov 2012
    Good information, Your information is very helpful for me. Thank you very much....

Comment

  1. Click to add

  2. Click to add

  3. Click to add

  4.    
     
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
     
      
       
Blogs feed
Categories

  • Tutorials (26)
  • Release (33)
  • Browsers (7)
  • Extensions (3)
  • Tip of the Week (10)
  • Videos (5)
  • Concepts and Theory (13)
  • Misc. (25)
  • Framework Constructs (6)
  • Mobile (6)
  • UI Widgets (5)
  • Blogs (1)
Archive
  • 2013 May (6)
  • 2013 April (10)
  • 2013 March (9)
  • 2013 February (12)
  • 2013 January (10)
  • 2012 December (9)
  • 2012 November (11)
  • 2012 October (6)
  • 2012 September (7)
  • 2012 August (8)
  • 2012 July (10)
  • 2012 June (8)
  • 2012 May (10)
  • 2012 April (7)
  • 2012 March (13)
  • 2012 February (10)
  • 2012 January (6)
  • 2011 December (10)
  • 2011 November (4)
  • 2011 October (6)
  • 2011 September (5)
  • 2011 August (9)
Home Web Mobile DataViz Server Wrappers Whitepapers Surveys Chrome Icenium Contact Us

Kendo UI framework is developed by Telerik - a leading provider of UI components for web, desktop and mobile applications. Trusted by over 100,000 customers worldwide for our devotion to quality and industry-best technical support, Telerik helps professionals maximize their productivity and "deliver more than expected" every day.

kendoui - powered by html5, css3 & jquery
get social
  • Twitter
  • Facebook
  • Google plus
  • RSS
Privacy Policy | Branding Guidelines
Powered by Sitefinity CMS

Copyright © 2011 - 2013 Telerik Inc. All rights reserved.