Archives

Blog Stats

Meta

Archive for the ‘jQuery’ Category

Here’s something I find myself needing to do often enough that it warrants a post. Here’s the situation…

I am dynamically displaying an unknown number of data items. The item itself is unimportant for this post, however, the item may contain some attributes that shouldn’t be displayed on the page all the time. Perhaps it’s a long description or information about how the item was last updated. Whatever it is, this data is better to be hidden unless someone actually wants to see it. This may be a good use case for some sort of panel that slides out when an “info” icon or “>>” button is clicked.

Making this happen with jQuery is pretty simple and consists of a few steps:

Wire up a “click” event to the button or text from where the panel will slide.

Using the clicked on element as an anchor, use jQuery’s offset() method to get the coordinates.

Either clone an existing element, such as a DIV, or create one on the fly and assign the following CSS rules to it:

Position – This should be set to absolute so the panel displays relative to its containing element.

Top – The distance in pixels, from the top of the containing element, where the panel should be placed.

Left – The distance in pixels, from the left of the containing element, where the panel should be placed.

Append the new panel to the container that is holding the list of data items.

Display the panel using a cool effect – or hide it.

A couple of notes before we get to the example. First, there are 2 ways to get an element’s position in jQuery – offset() and position(). You can read the descriptions to understand what they both do, but offset() typically works for me. I’m also using the ‘slide’ toggle effect from jQuery UI to slide my panel from left to right with the toggle() method.

UPDATE: 12/17/2010 12:55 AM CST – Thanks to Dave’s comments below, I learned that the script service handles object serialization to JSON for me. This means that if your return type is that of an object, it will automatically serialize this object to JSON. If you want to create an anonymous object, such as you may do from a LINQ query, just set your return type to “object”. I thought I had to turn that into a string, but that’s not necessary. Thanks again Dave. I also removed the [ScriptMethod] attribute, which is isn’t necessary and actually causes the JSON returned to be a string and not a JSON object.

I’ve not done anything real meaningful in Web Forms in some time, so I was very surprised at how much trouble I had trying to call a simple HelloWorld service from a jQuery Post and have it return some JSON back to my screen. It took a couple hours to finally get it right, and I know I’m not the only one. There are Stack Overflow posts about this and many blog posts as well. Unfortunately, as helpful as those posts were, it seems that I was still missing things… the things I’m going to cover in this here post.

ASMX Web Service

First, let’s start with the old school web service that I’d like to use to communicate with the client. Sure I could go WCF, but an ASMX is just fine for my needs and darn simple. The important things to note on the service:

To call a service from JavaScript, the service class must be decorated with the [ScriptService] attribute.

The service method should not decorated with the [ScriptMethod] attribute, only the [WebMethod] attribute. The ScriptMethod causes the return JSON to be a string that needs to be deserialized on the client. Without it, it comes down as a valid JSON object, automatically deserialized by jQuery for me.

If you are going to return a hardcoded JSON string for jQuery to parse, it has be formated with double quotes around the names and properties. I was using single ticks, which I have gotten away with in some cases, but not here (return “{\”response\”:\”Hello World\”}”).

Mark the return type of the method to “object” if you want to return with an anonymous object from a LINQ query or something like that.

AJAX and jQuery

Now for the jQuery, for which I’m using version 1.4.4. Here’s the things that tripped me up:

I was using a JQ $.post call in my web pages to communicate with the server. That caused me some problems in that the data was always returned as XML, no matter what I tried. Knowing that $.post is a shortcut against the $.ajax method, I switched to using that so I could explicitly set the contentType to “application/json”. I do realize that I can probably set that on the $.post method, as I’m pretty sure I’ve done that in the past, but that can cause confusion, especially with new developers.

If you are accessing more than one service in more than place, create a utility method or use the $.ajaxSetup method to configure the defaults.

If you don’t set the dataType to “json”, the response data is returned as xml.

If you don’t pass empty data when there are no parameters needed for the service, the response data will be returned as xml.

The dictionary passed to the service in the data parameter must be quoted or the service will throw a 500 error. Web Service parameters are passed with the name of the parameter as the key (see example).

This is discovered soon enough, but the response from the service comes wrapped in another JSON object, available at the ‘d’ key. If the value for ‘d’ is a JSON string, it will have to be deserialized into a proper JSON object. I use jQuery’s $.parseJSON function for that. This example will return ‘d’ as a proper JSON object.

Authorization and Authentication

Any ASMX service written in our web project will be available to the world. If you are using a ROLES and MEMBERSHIP provider and your site requires authentication, use the <location> tag in your web.config to lock down the directory where you put all your services. In my example, I’ve put all my services in a WebServices directory and only authenticated users in the Admins role have access.

Sometimes there is a need to put certain elements within a FORM in a JQuery Dialog. This sounds simple enough, but unfortunately when the dialog is displayed, the form elements can get lost as they get added outside the Form’s DOM.

The solution is simple, append the dialog element to the form. Here’s an example of how it’s done.

<script>
$(document).ready(function() {
//define the dialog for later use
var dlg = $('#AddressVerification').dialog(
{
autoOpen: false,
closeOnEscape: false,
modal: true,
width: 550
}
});
//This is where we tie the dialog content to the parent form
$("#AddressVerification").parent().appendTo($("form:first"));
//other code not pertinent to this
});
</script>

When there are errors or important information that you need to call out to your users, it is important to make it unmistakably noticeable. You want to stack the odds in your favor as much as possible that the user will see your call outs and act on them accordingly. Unfortunately, the ValidationSummary in ASP.NET and ASP.NET MVC comes very vanilla. You can change the appearance in MVC by defining the “validation-summary-errors” CSS class that is set to the ValidationSummary by default, but this isn’t always enough. The same goes true for an Information Box, which is what I call a box that contains important information that I want the user to see.

It is very typical for users to gloss over these important messages when they are rendered as text only. Placing the text in a colored box with a brightly colored border can help, but I’ve still experienced frustrated users claiming that registration is broken because they miss the message that says their email has already been used. To combat this, it’s a good practice to use familiar operating system icons for Error, Information, Warning, etc. Most users will recognize familiar icons and have learned to pay attention when they see them.

Here’s an example of what we’re going to achieve:

Styling the “Callout Box”

I use the same technique to style all my callout boxes. It’s very simple to do with JQuery, CSS and a few icons. I’ll demonstrate this for both an Error and Info callout.

First, the CSS classes. Each type of callout (error, info, warning) will require 2 classes. One class will style the box that contains the text and the other will be used to hold the applicable icon.

The HTML used to put the icon in the callout box requires nested DIV or SPAN elements. I don’t want to depend on my memory to always add the nested elements each time I want a callout, I want to simply write something like this:

That’s where JQuery is able to help us. By using the prepend function, we can have the appropriate icon automatically injected into our callout box. We do this by adding the following to our JQuery ready function in our Master Page.

$(document).ready(function() {
$(".infobox").prepend("<span class='infoimage'>&nbsp;</span>");
$(".errorbox").prepend("<span class='errorimage'><span class='errorhead'>Looks like we have a small problem...</span></span>");
});

Pretty simple, right? Here’s what’s happening here. The script is finding the elements styled with the infobox and errorbox class and sticking in a SPAN element styled with the corresponding icon class. The errorbox gets the additional heading added here as well. You could do the same thing for Warn, Question or any other conventions you wish to follow.

There are several terms to describe the common UI technique of having 2 dropdown lists, with the selections of the first dropdown changing the options of the second. Common terms for this include Dependent Dropdowns, Context Sensitive Dropdowns, Contextual Dropdowns and probably others.

I recently had a requirement for this functionality in a control in an ASP.NET MVC project. When I searched for some samples on how to do this in JQuery, I realized that all the samples I found used AJAX to populate the second list. In this particular case, it made more sense to keep everything on the client, so that’s what I developed. This post is about how I accomplished this using JQuery, JSON.NET and a ViewModel with a couple extension methods. If you’re looking for ways to do this with AJAX, you’ll have to read one of the many other examples in the blogosphere.

The Requirement

The user needs a way to choose a color for a product. The chosen color is categorized under a parent color (Blue.Baby, Blue.Sky, Yellow.Banana, Yellow.Lemon). The user should be able to first pick a parent color and then view a list of all child colors from which to pick. The catalog of color selections is stored in a database and should be used to drive the dropdowns. The dropdowns are just a helper as the user is able to input any color name they wish, regardless of whether or not it appears in the second dropdown. Up to 5 colors can be chosen per product, so the color selection should be a control that can be repeated on a view, however, this post will ignore that requirement and show how this can be accomplished in a singular fashion.

The Object Model

The ViewModel that drives the View where this functionality resides contains an IList<VendorColor> property, which will be used to populate the dropdowns. The VendorColor class looks like this:

In order to keep everything on the client, we’ll need to get the pertinent data from the collection of VendorColor objects to the View so it’s accessible by JQuery and JavaScript. To do this, 2 extension methods were written to serialize the required data to JavaScript objects.

First, we need to gather the distinct PrimaryColor values from the list of VendorColor objects and get them into an array. Here’s what that extension method looks like.

The next extension method will be used to serialize the entire collection of VendorColor objects to JSON objects that we can later parse with JQuery and fill our dependent dropdown list. This is ridiculously easy with the help of the awesome JSON.NET library. Check out what can be done in one line of code!

Now let’s tie it all together by seeing the view and all the javascript that makes this work. It should be noted that my view is utilizing the latest version of the JQuery library.

//use vars for my controls so JQuery and Javascript won't have to retype each time
var primaryDd = '#PrimaryColor';
var secondaryDd = '#SecondaryColor';

Now the script that makes all this work, complete with comments. In the real world, this is stored in an external .js file, as it should be. This keeps the views cleaner and Google favors it for SEO. Keep in mind that the script is using the vars defined above.

JQuery and ASP.NET Ajax has made it very easy to use AJAX to accomplish dependent dropdowns. In many cases, it’s wasteful and unnecessary to go to the server for this information over and over again. In such cases it can be advantageous to do this purely on the client. Using JSON.NET to serialize objects from .NET to JSON and using JQuery and its “grep()”, “each()” and “val()” methods to get the right data and handle population and selection. This solution didn’t take too long to develop, but if you know a better way, I’d love to hear about it.