Tag Archives: AJAX

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.

Model Binding: HTML Templates

url4

 

The client-side migration revolution has not left markup untouched. Given thatclients making service calls and rendering the results has become such a common way for web applications to work with data, especially as mobile application use is on the rise, a good deal of attention has been given to the rendering aspect of using service data.
The standard way of dealing with data returned via AJAX was to use JavaScript to concatenate the data into strings of HTML and then dynamically write that HTML into the DOM. Although the basic principle is the same, mechanisms have been developed in recent years to make this process easier and more modular. Binding data to HTML templates is a popular way to do this, and using it has even given rise to a pattern commonly called MVVM.

MVVM

MVVM stands for Model-View-ViewModel and describes a client rendering design pattern.

  • The Model represents your actual data, such as might be pulled from a database or a service.
  • The View is the actual UI that renders the ViewModel, which will generally be HTML in the case of typical web application development.
  • The ViewModel is Model data that has been shaped specifically with the goal of binding this to a View that will render the data.

This may not sound all that different from the MVC or MVP patterns, but one of the things that makes the MVVM pattern a little more exciting is that changes to the ViewModel can update the View and the Model immediately.

Let’s consider the traditional client-server way of editing data. If you want to add a new customer in a web application:

  1. Pull up an HTML form and make changes to the form.
  2. >Click Submit so the page posts this data to code that writes it into the database.
  3. The page refreshes with any new information such as Customer Id.

Now let’s consider using MVVM to edit data. With the MVVM pattern, a ViewModel sits between the View (the form) and the Model (the data from the database), which gives you flexibility on when and how these updates happen >and renders the changes in real-time. If you want to add a new customer using MVVM:

  1. Fill out the Add Customer form.
  2. Click Submit, which adds the customer to the ViewModel.
  3. This change automatically updates an Added Customers grid at the bottom of the page with no refresh.

At this point you can decide if you want the new customer to be saved directlyto the database. If you do, then as soon as your server-side code saves the customer and gets the Id, it can put the Id into the ViewModel which automatically updates any UI elements bound to it.

You could also keep the “Added Customers” in the ViewModel but not save any of them until the user clicks the Commit Changes button. This allows theuser to add, update, or delete all kinds of operations on that data with a UI thatresponds immediately to changes but doesn’t commit anything to the database until it’s told to.

The main point is that in MVVM, the ViewModel is directly bound to the View, so any changes to it automatically update the View. This adds a huge level of responsiveness and options when writing web applications. Some applications are referred to as Single-Page Applications because the MVVMpattern enables users to do everything on a single page bound to a modifiable ViewModel.

Binding ViewModels to HTML

Much like AJAX, there are a number of JavaScript libraries that have already been written to help you with the process of binding an HTML UI to a ViewModel. The basic principle behind them all is that you create a snippet of HTML and use attributes or JavaScript functions to mark off the dynamic partsthat will get their data from the ViewModel.

When a web page containing an HTML template is requested, an AJAX operation gets data from a service. This data either directly becomes or is incorporated into a JSON ViewModel, and the JavaScript binds this ViewModel to the corresponding places marked off in your HTML. Any changes to the JSON ViewModel will automatically update the UI pieces that are bound to them.

Like AJAX, there’s nothing stopping you from writing all the code for this process yourself, but a number of libraries exist that already do this. One popular library for binding JSON ViewModels to HTML templates is Knockout.js, and Microsoft includes it by default in Web API projects. There are other options however, such as Pure, Mustache, or JTemplates. Also like AJAX, no Microsoft-specific technologies or platforms are required to use HTML templates. On the client/consumer end of HTTP web services, you are free to use whatever you like, all the way from static HTML to PHP to JSP to anything in between. It’s all HTML and JavaScript at this point.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API Model Binding and Media Formats course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

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.