Tag Archives: jQuery

MVC, Ajax, and jQuery

Screen Shot 2012-10-18 at 11.46.55 AMMany people see Ajax as the technology that saved the web, that made it possible to create much richer Web 2.0 applications than was ever possible using just HTML and plain old JavaScript. Part of the key to Ajax’s success is that it uses standards-based, widely implemented technologies instead of proprietary tools like Flash, Air, Silverlight, and many others that have sprung up to overcome the perceived limitations of HTML. Ajax has the benefit of ubiquity: all modern browsers have an implementation of JavaScript and
include the key object used to make asynchronous calls to the server, XmlHttpRequest.

Ajax is a powerful web technology because it makes pages far more interactive to the user, performing actions and updating parts of the page without requiring a full page refresh and accompanying flash of a blank page. This is one of the biggest visual differences between a web application and a rich client application, and gives the illusion of running on the client machine even though it is in a browser. An “Ajaxified” page feels faster to the user and reduces the load on the server by requesting small chunks of data and HTML rather than the content of full pages on every user action. Ajax is inherently asynchronous, so it leaves the user interface responsive to the user even if the last operation takes a while to complete.

Ajax is not, however, a panacea. It is a bit past its prime as the buzzword du jour of the last decade, but it is still too easy to get carried away with it and use it as though it solves all web problems. Here are a few of the problems:

  • Ajax requires that JavaScript be enabled on the client browser, not something you can assume in this day and age of security threats.
  • Unless you plan carefully to hook your pages into the browser’s history, the user won’t be able to use the back button to return to a previous page state. This is something that can be a bit unsettling to a user, when the back button takes them to an entirely different page rather than an earlier state of the same page.
  • By default, users also won’t be able to bookmark a link to the one product out of your entire catalog that they want to buy for their kid’s next birthday. This is because the application has to build in support for supporting page state through the URL.
  • Sites that make heavy use of JavaScript may come with many hundreds of thousands of bytes of script files. Even with caching, that can slow things down dramatically.
  • It also doesn’t help that JavaScript is notoriously slow, although modern browsers are improving performance.

Nevertheless, a well-designed site can handle most of these problems, both through careful design and judicious use of Ajax and other client-side features. The vast improvement to the user experience on sites that use Ajax can easily be worth the potential negatives, particularly since careful design can largely negate the problems.

In the purest sense, it may seem like nonsense to talk about MVC and Ajax together, since they occupy entirely different worlds within a web application. MVC is a server-side technology: the browser rendering pages doesn’t have a clue about models, views, and controllers. All that the browser sees is HTML and whatever the view embeds in the page it sends to the browser. Likewise, Ajax is a client-side technology that makes clever and sophisticated use of JavaScript and HTML’s document object model (DOM) to make pages far more interactive than is possible with just HTML. Of course, Ajax makes calls to the server to receive data used to update the page in response to user actions, but most of the time that is a clean, well-defined interface, often using some kind of web service implemented on the server. On the face of it, it doesn’t seem like there should be much to cover in a joint MVC/Ajax chapter, right?

Well, no, not right (as you probably guessed, based on the fact that this chapter exists). It turns out that there are some nice synergies in using the two technologies together. This is because MVC includes features that make it easier to implement custom Ajax features in a web page and because Ajax on the client can interact with action methods on the server to more effectively respond to user requests. This chapter will introduce you to these two broad ways that MVC can work together: on the server, mostly through features you can include in view definitions, and on the client in the client-side JavaScript you can include in a page. One nice thing about using these technologies together is that you can avoid writing much, if any, JavaScript code if you want, or you can write as much as you want to really make your pages come alive for users!

James Curtis

This post is an excerpt from the online courseware for our MVC 4.0: Validation and Working with Ajax written by expert James Curtis.

James Curtis  is a .NET Developer that primarily works in the UX space. He has worked on and for several large projects alongside Microsoft Consulting. James has spoken at several code camps about UX development for ASP.NET and SharePoint. He is an active participant in the development community tweeting and blogging about several topics in the UX area. James is an active consultant and is also assisting in several Start-ups contributing his UX experience.

Soften Your Look with jQuery

As mentioned in a previous blog post, Microsoft made two commitments when it decided to embrace jQuery as its one and only client-side JavaScript library. First, they were going to replace their Ajax Library with jQuery in every appropriate ASP.NET Web technology, including both Web Forms and MVC applications. Second, they would contribute plugins and other extensions to the jQuery Library, primarily by adapting their work on enhancements for the Ajax Library to the jQuery Library. These contributions might end up in the core jQuery Library, as official jQuery extensions, or, as a last resort, freely distributed, open source extensions.

In this article, we’ll discuss one such extension.

Creating Rounded Corners

rounded corners in AJAX

Putting rounded corners on elements is a desirable feature to soften the look of a Web page. But it is surprisingly hard to do well across all browsers, both because there are so many ways to accomplish the effect and so many variations among browsers. Web designers have long resorted to using images, even though CSS and other Web technologies support rounded corners. ACT has a nice RoundedCorners extender that applies the effect to HTML elements, letting you vary the appearance by changing the radius of the corner, which corners are rounded, and other options, giving a lot of flexibility for creating a nice page appearance. The Figure below shows the RoundedCorners extender demo from the ACT sample pages, with options set to round the upper right and lower left corners of the image.

Rounded corners seems to have been an area of particular creativity for jQuery plugin developers, probably because of the cross-browser issues and the lack of a single right way to achieve the effect. The result is a lot of plugins that let you get as creative as you want. We chose one of the simpler plugins to use on the Toolkit page, shown in the Figure below. The first box is a plain, square div element and the second has rounded bottom left and upper right corners using the Cornerz plugin for “bullet proof corners.” The plugin has a few options such as to set the border and background color, set the radius, and select which corners to round. But overall it is a pretty simple plugin that does its job quite well.

rounding the corners of a div element

The page uses the following HTML code for the Rounded Corners section. It is very simple markup, using a couple of div elements that each contain a p and cite elements.

The page uses a twain class to style the div elements, setting padding and the background color. Padding is important for most rounded corner plugins, providing room around the text to round the corner. You could have a border of a different color—as is commented out in the style below—and the border would be rounded as well.

Then the page includes a single JavaScript statement to round the corners, shown in the following code. It calls the cornerz method, passing two optional arguments. fixIE attempts to overcome a problem with some inline elements in Internet Explorer due to a wrong reporting of width, and the second specifies that only the top right (tr) and bottom left (bl) corners should be rounded.


ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

jQuery Plugins, Easy as 1,2,3

114-jquery-plugin

Despite the usefulness and comprehensiveness of jQuery, it doesn’t do everything it could to make your JavaScript coding life simpler. Frankly, you wouldn’t want it to do everything! It doesn’t even pretend to be comprehensive, if only because that would make the size of the core library enormous. The bigger the library is, the less likely that it will see wide use because it would have such a big impact on Web page performance and bandwidth, even if the browser effectively caches the library after its first use.

That’s why jQuery includes rich support for extensibility. You can create your own plugins, utility methods, and other features that closely integrate with jQuery itself. If jQuery doesn’t do something you need, or doesn’t do it exactly as you need, always start by doing a search for jQuery extensions online to see if anyone else has already solved the problem. If not, you can write your own extension and use it in your Web pages, and share it with the world if you’re so inclined. It is not very hard to write jQuery plugins.

Plugin Conventions

The jQuery community has created an enormous number of jQuery plugins, and over the last few years a few general guidelines for plugin development have emerged. You should always strive to follow these guidelines, because by doing so your plugins will integrate into jQuery effectively and will have the look and feel of jQuery, making your plugins easier to use.

  • Always name your plugin file using the format jquery.myPluginName[-version].js. The major and minor version numbers are optional, but by using this format for your plugins you follow the general convention, make it easy to find your plugin in a set of script files, and reduce the chance that you have name collisions.
  • Choose the name for your plugin carefully. If it becomes popular, you’ll not want to share a name with other plugins. Some authors include a subprefix after “jquery” in the name. So, if AppDev were to begin producing and sharing jQuery plugins, we might name our files jquery.appdev.myPluginName[-version].js. That would reduce the chance of filename collisions. And name the plugin method carefully to avoid collisions with other jQuery methods and plugins others may use in their Web pages.
  • Plugins can either return a scalar value or the matched set so that you can chain jQuery methods together. If it makes sense for the plugin, you should always return this to support chaining.
  • Always write your plugin so that it is usable with both the full jQuery method name and its $ alias.
  • Avoid a long list of arguments for your plugin. It’s fine to allow lots of options, almost mandatory, but limit yourself to a small number of arguments and make one of them options, through which the user can pass multiple values. This will mimic how most jQuery Library methods work.

It would be well worth your time exploring various popular jQuery plugins available and learn the best practices and conventions that other developers are using. Even if you don’t share your plugins with the world, you can and should take advantage of the things that other people have found that work.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

jQuery: Sticking to Commitments

Microsoft made two commitments when it decided to embrace jQuery as its one and only client-side JavaScript library. First, they were going to replace their Ajax Library with jQuery in every appropriate ASP.NET Web technology, including both Web Forms and MVC applications. Second, they would contribute plugins and other extensions to the jQuery Library, primarily by adapting their work on enhancements for the Ajax Library to the jQuery Library. These contributions might end up in the core jQuery Library, as official jQuery extensions, or, as a last resort, freely distributed, open source extensions. We discuss one such extension, watermarking, below.

Watermarking

Watermarking is a cool, useful, and interactive way to prompt a user for the information that should go into a text box on a form. When the input element is empty, the watermark text appears, usually grayed out. When the user enters the field, the watermark text disappears and whatever the user types appears in the field. You can determine the styling of the watermarked element both when the watermark text appears and when the user text appears.

The Ajax Control Toolkit has a nice TextBoxWatermark extender that you can attach to a server-side ASP.NET TextBox control. Figure 1 shows the TextBoxWatermark demo from the ACT sample pages.

url

Figure 1. The ACT TextBoxWatermark demo.

There are many watermark jQuery plugins, but one of the simplest and easiest to use is the TinyWatermark jQuery plugin. You can use it with any input or text area element by specifying the watermark CSS class and the text you want to display when the input element is empty. You have the option of supplying the watermark text either as the value of the title attribute of the element or as the second argument to the watermark method. When the user submits the form, the plugin removes the watermark text. The jquery.tinywatermark- 3.1.0.js plugin file is a mere 623 bytes, and that’s not even minified or compressed.

Figure 2 shows watermarking in the sample page. The user has moved to the first text box and entered text, so the watermark text is removed and the text box has its default appearance. The other two text boxes show the watermark text and styling.

Screen Shot 2012-10-19 at 9.28.36 AM

Figure 2. Watermarking in action in the sample page.

The following HTML creates the three text boxes on this part of the page. Notice that the first two text boxes have a title attribute with the watermark text, while the third will have the text set programmatically. The first two are assigned the watermarked class as the means to identify them to the plugin that they are to have watermarked text inserted. The last one is assigned to the watermarkedAlt class to let the code treat it differently, as you’ll see in a moment.

 

The plugin uses the following CSS style to change the appearance of the elements that are watermarked. It merely sets the background color to #FFFF99, which is officially Pale Canary Yellow, and changes the font color to a medium gray.

 

The crux of the watermarking code is the following two statements, contained within the jQuery ready method so they’ll fire only after the page’s DOM is loaded in memory. The first statement watermarks the name and email text boxes on the page, using the title attribute’s value as the watermark text. The second statement watermarks the third text box, providing the watermark text as the second argument to the method. Both statements tell the watermark method to use the watermark CSS style to display the input element and watermark text.

We usually find that the first form of the watermark statement, using the title attribute for the watermark text, to be more useful and practical when there are more than a couple of elements on the page you want to watermark. That way the watermark text is with the element rather than separated in the page’s script code. But you’re free to use whatever form works best for you.

You can use whatever class name you want to identify the input elements to be watermarked, as well as the name of the CSS style used to format the elements with watermark text. The plugin is surprisingly functional for such a small size!

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

Pulling Out the Big Gun: The Ajax Method

Screen Shot 2012-10-18 at 11.46.55 AM

 

All of the Ajax features in jQuery are convenience methods that make using Ajax fairly easy for the most common scenarios. But when those convenience methods don’t work for you, you can pull out the big Ajax gun in jQuery: the ajax method. This is the method that all of the convenience methods ultimately use to make the actual call to the server. They do this by performing all the setup necessary and setting default values for various arguments that work for the particular Ajax task at hand.

You can make use of the ajax method directly to handle the scenarios not easily handled—or not handled at all—by the convenience methods. It has the deceptively simple syntaxes shown in the following code, taking just one or two arguments, url and options. With the first syntax option, you can pass the URL for the Web service and optionally follow it with as many option settings as you need. Or you can just pass a value for the options argument, one of which could be the url. This method is the embodiment of the saying that the devil is in the details, and providing the right options for what you want to do is the details you need to wade through to make the method work for you.

Let’s look at a simple example of using the ajax method by rewriting the ‘Hello World’ sample below. Here is the code from that sample:

The HelloWorldAjax.html page in the sample project uses the ajax method directly to make the Ajax call to the server. It uses the type option to make a GET call and the url option to specify the location of the Web service. Like the get and post methods, the ajax method is a utility function that doesn’t directly update a matched set of elements, so the method call uses the success event option to define a function to update the div elements on the page with the response text. This anonymous function uses the text method of the response object to extract the text from the XML returned from the Web service method and the html method to update the div elements.

The figure below shows the results of clicking the Get Info button on the page, where the code updates the three div elements on the page.

As you can see, using the ajax method is more complex than using the load method, both because you have to provide appropriate option values as well as because the method doesn’t directly update a matched set of elements. You have to write a function for the success event to update the page.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

AJAX: The Technology that Saved the Web

ajax-jquery

 

Many people see Ajax as the technology that saved the Web, that made it possible to create much richer Web 2.0 applications than was ever possible using just HTML and plain old JavaScript. Part of the key to Ajax’s success is that it uses standards-based, widely implemented technologies instead of proprietary tools like Flash, Air, Silverlight, and many others. All modern browsers have an implementation of JavaScript and include the key object used to make asynchronous calls to the server, XmlHttpRequest (XHR).

Ajax is a powerful Web technology because it makes pages far more interactive to the user, performing actions and updating parts of the page with data from the Web server without requiring a full page refresh and accompanying flash of a blank page. This is one of the biggest visual differences between a regular Web application and a rich client application, and gives the illusion of running on the client machine even though it is in a browser. An Ajax page feels faster to the user and reduces the load on the server by requiring small chunks of data and HTML rather than the content of full pages on every user action. Ajax is inherently asynchronous, so it leaves the user interface responsive to the user even if the last operation takes a while to complete.

Updating a Web Page Using Ajax

Using Ajax to call a Web service on the server is one of the best ways to dynamically update part of a Web page using Ajax. You can request only the data you need to save bandwidth and thereby get the best performance, and you can do anything you want in the Web service to retrieve data. You can read files, hit a database, call other Web services, format the server’s hard drive (although we don’t recommend this one), whatever you want. Best of all, Ajax and jQuery can handle several different data formats, so you usually won’t have to write any client-side JavaScript code to parse the response before using it.

There is really not all that much different when using the load method to retrieve data from a Web service rather than static HTML files. The HelloWorld.html sample page uses the HelloWorld Web service in AjaxServices to retrieve a string, which the page uses to update the content of three div elements on the page, as shown in Figure below. The Web service increments the number with each invocation, so that you can see that the page updates with each click.

jQuery Ajax

The Web service that the page calls is just about as simple as a Web service can be, using the following code. The HelloWorld method returns a string consisting of the requisite Hello World along with an integer that increments with each call. There is nothing special about this Web service that indicates that the client page will use jQuery to invoke the method.

The following code defines the body section of the page. The only interesting thing here is that there are three div elements, which the page uses to demonstrate that using a ‘div’ selector for the load method will update all three of the matching elements. There is also a style in the page that sets the divSays1 element to 24pt font size, just to vary things a bit.

The following code defines the click event function for the button. Yes, that’s all the code you need to call the Web service and update the contents of the div elements with the string retrieved from the Web service. The sole argument in this very simple example is the URL with the name of the desired method appended as a path element.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

jQuery: Compressed vs Uncompressed, the Choice is Yours

When you go to the jQuery Web site to download jQuery files, you’ll find that you have two file options, shown in Figure 1: a production version (compressed) and a development version (uncompressed) of the core jQuery library. The files sizes for version 1.5 are quite different: 29KB and 207KB.

jquery

Figure 1. The download panel on the jquery website.

TIP: You can download older versions of jQuery using the Download link on the jquery.com Web site (not shown in Figure 1) as well as plugins and other extensions.

The difference in the two files is that the development version is human readable with lots of whitespace and generous amounts of comments to help you understand the code. Figure 2 shows the first few of the 8,177 lines of code in the file open in the Visual Studio code editor. We recommend that you use this version of the file, named jquery-1.5.js, while you learn jQuery and in development. That way, you can use the Visual Studio JavaScript debugger to step into jQuery both to understand how jQuery works and to understand why your code might not be working the way you expect (and to perhaps find a bug in jQuery). Loading a 207KB file on your local development machine should take no time at all, so it won’t slow down your coding.

jQuery library file

Figure 2. The development version of the jQuery library file.

Then, when you’re ready to deploy your site, use the 29KB production version in the file named jquery-1.5.min.js, where “min” stands for minified. This file has had all of the unnecessary whitespace removed, variable names shortened, and other compression tricks applied to get the size of the file as small as possible. As you can see in Figure 3, the file consists of the readable comments at the top of the file, and a single line of code; you’ll see that line is 83,996 characters long if you scroll all the way to the right. If you scroll through the one line of code, you’ll find that it is almost impossible to follow the logic. We humans just weren’t built to process such condensed data! But a browser knows just what to do with it.

production version of the jQuery library file

Figure 3. The production version of the jQuery library file.

The benefit of the production version is that users have to download a much smaller file when they load your page, and you save a bit on your bandwidth bill. Even though the browser will cache the file for subsequent page views, this will mean that the initial page load will be noticeably faster, particularly over slower connections.

TIP: You can get the size of the development version even smaller if you use gzip compression in your Web site.

This post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

7 Benefits of jQuery

jquery1

 

jQuery makes using a Web page’s DOM (document object model), adding effects to the page, animating elements, and executing Ajax calls to the server extremely simple, hiding the complexity of the underlying JavaScript. There are a number of benefits to using jQuery instead of writing your own raw JavaScript or building your own library.

  • jQuery is lean and mean. Please forgive the cliché, but it is an apt way to describe the library. The minimized size of version 1.5 of the library is a mere 83KB, only 29KB when gzip’d. That is probably smaller than a single photo on many Web sites, and the browser only has to download and cache it once for use across all your pages. If you use a content delivery network (CDN), the user’s browser can cache it across many Web sites rather than download it for each. jQuery packs a lot into a very small size.
  • One of the primary benefits of jQuery—a benefit shared with some other JavaScript libraries—is that it seamlessly handles crossbrowser issues. JavaScript implementations differ among browsers to varying degrees, and it can cause a developer to prematurely and severely age to get everything working across browsers with JavaScript. Relax: the authors of jQuery have done most of the work for you.
  • jQuery uses a simple, clean, powerful syntax that makes it easy to select the DOM elements on the page you want to change with JavaScript and allow you to chain actions and effects together for efficient code. It is quite common to replace a dozen or more lines of JavaScript with a single line of jQuery code. jQuery uses the CSS (Cascading Style Sheets) version 3 selector specification for selecting elements, so you don’t have to learn a different syntax to use jQuery. This assumes, of course, that you’re familiar with the CSS3 syntax.
  • jQuery is highly extensible. As mentioned earlier, the core jQuery library is kept tight and focused, keeping out non-essential features. It also provides a plugin framework that makes it easy to extend jQuery, and there are both official jQuery plugins as well as thousands from third parties. This way your page has to download only the specific set of features it needs. Any time you need a feature not included in the core jQuery library, there is a good chance that someone has already written a plugin that does what you need.

TIP: You can find a list of available plugins at jquery.com, the home of jQuery, with user ratings to help you find the best ones.

  • jQuery supports building pages using unobtrusive JavaScript, an approach to using JavaScript in Web pages. Among other things, unobtrusive JavaScript is concerned with the separation of functionality between a Web page’s structure/content and presentation. This keeps nuggets of code out of HTML elements on the page, such as with event attributes such as onclick. Instead, you wire up event code in a script block, keeping the behavior implemented in code separate from the structure of the page.
  • One of the goals of jQuery is to make things that are hard in JavaScript easy when using jQuery. So jQuery includes many utility functions to do things like trim strings, parse JSON data, check whether one DOM element is within another, and search array elements using a filter.
  • jQuery is one of the most widely used JavaScript libraries available, with support from some of the most heavily trafficked Web sites in the world. According to the jquery.com Web site, Google, Amazon, IBM, Microsoft, Twitter, Dell, CBS News, Bank of America, and many others use it on their Web sites, and it is in use in many open source projects including Mozilla, DotNetNuke, and WordPress. Such widespread use ensures that jQuery will receive active development support for years to come, and a vibrant user community has formed around the library.

If you want to add rich user interactivity or Ajax features to your Web site, there really is no reason not to consider jQuery. Once you learn what jQuery can do and how small and efficient it is, it’s easy to understand why Microsoft abandoned its own Ajax Library in favor of jQuery! Even if you begin using jQuery and find some highly specialized situation that the library doesn’t support, you can always fall back to writing your own custom JavaScript for that one situation.