Ajax Gotchas with jQuery and ASP.Net MVC

February 12th, 2010 Phil No comments

I’m refactoring an application at the moment that has been throwing out all sorts of surprises and complexities that I just wouldn’t have expected.

Often when coding a site or web application, you have a very basic task that you want to accomplish, can envisage exactly how you might achieve that ask, but when it actually comes time to build it, small quirks, faults and unfamiliar errors can cause a disproportionate amount of hair-pulling and crying out to various deities for mercy.

This post looks at a couple of brick walls I ran into while including Ajax functions in my ASP.Net MVC application and will hopefully help you if you encounter similar problems.

Read more…

Quick Hits – jQuery.Map()

February 11th, 2010 Phil No comments

This post is the first in a series that looks at some of the less-popular jQuery functions and describes practical uses for them.  In each brief post, I’ll outline a problem or situation and look at how I used a jQuery function to provide a quick and easy solution.

My focus today is the jQuery.map() function.

Introducing jQuery.map()

In a post from ages past, I looked at a few of the more obscure jQuery functions and what their purpose was.  Among these was jQuery.map().  To quote from the documentation:

Translate all items in an array or array-like object to another array of items.

So let’s look at how I used it.

The Problem

I have an ASP.Net  MVC application that lists of the available roles that users can be assigned to.  I’ve rendered this list as you’d expect in an unordered list.  I’ve then used jQuery UI to make this list selectable.  When the user selects one or more roles and clicks a save button, I want jQuery to capture the selected items and post them using Ajax to my application.  Simple.

The Solution

Without going into detail on the rendering of the list or buttons, here is the code to handle the “Save Roles” button click event.

$('#save-roles').click(function () {
    var user = $('#users option:selected').val();
    var roles = $.map($('#role-list li.ui-selected'), function (n, i) {
        return $(n).text();
    }).join(',');

    $.post('/Account/AssignRole', { username: user, roleNames: roles }, function (data) {
        console.log(data);
    });
});

My MVC Action takes two arguments: “username” and “roleNames”:

public JsonResult AssignRole(string username, string roleNames)
{
...

My jQuery routine has very little code to accomplish what I need.  The key part we’re looking at is the $.map() function.  This takes an array as the first argument; in our case we’re passing in an array of DOM elements: the list items that we’re telling jQuery to go and get:

$.map($(‘#role-list li.ui-selected’), function…

The second argument is the callback. This can be thought of loosely as the function to execute once our initial $.map() task is ready.  In our case, I’m returning the text of our retrieved list items and storing them in a variable called roles:

function (n, i) {
return $(n).text();
}

Finally, since all this is returned as an array, I only want a comma-delimited string, so I’ll finish my $.map() operation by adding the JavaScript .join() function on the end to combine all the values into one.  The result looks something like:

“Administrators, Power Users, Restricted Users, Users”

Simple.  I can now post that information off to my JsonResult MVC Action.

This function is actually quite handy for playing with lists and collections on the page and often saves a lot of iterating through your arrays with for loops.

Hope this helps.

Serializing Entity Framework Objects into JSON Using ASP.Net MVC

February 4th, 2010 Phil No comments

I’ve been working with the Entity Framework 4 on a new MVC2 application recently and one apparently simple task had been doing my head in for a full day. The problem was when I tried to serialize a list entity object using the Json method in a JsonResult action. Every time I tried, no matter how I approached the task of retrieving the records, I’d always see the following exception in my Json response:

A circular reference was detected while serializing an object of type ‘System.Data.Metadata.Edm.AssociationType’.

The really frustrating part was that when I was debugging my application in Visual Studio, everything appeared to be working just fine. Connections were established, records were returned and could be passed into my List object.

As it turns out, the problem appears to be a native issue with the DataContractJsonSerializer support for Entity types.  In short, Entities that have relationships (i.e. two-way) with other Entity types cannot be serialised through Json.  For example, a Customer table connected to an Orders table will not translate well into Json serializing because a Customer may have many orders and an Order is associated with a Customer.

Eugene Osovetsky, Program Manager (Connected Framework Client) at Microsoft has the following to say about the issue:

The lack of DataContractJsonSerializer support for Entity types is certainly an important feature hole, and we will certainly be investigating possible solutions in future versions. Unfortunately, the current serialization model only allows one projection per type, EDM type generation only allows generating IsReference=true types, and there is no standard way of encoding references in JSON. Clearly one of these 3 constraints has to give for this to be solved, but all have problems. Multiple projections would be great, but may be complex to understand/use and would be a major new feature (it is on our radar for the future).

One approach to solving this problem has been:

…to make the serializer ignore the properties of type EntityReference, using an empty implementation of a class deriving from JavaScriptConverter and registering it using the RegisterConverters method of the JavaScriptSerializer object.

However, I feel that for most cases, this is overly complex and requires more thought than most situations would likely demand.  A better approach IMHO would be to take a collection of results and extract your required properties into a new anonymous type.  The thinking here is that if you’re returning Json objects through Ajax calls, you’re probably only interested in values rather than the full behaviours of a given object.  Therefore, the following code sorted my problem out adequately:

public JsonResult Orders()
    var results = from Ord in databaseContext.Orders
              select new
              {
                  OrderID = Ord.ID,
                  OrderTitle = Ord.Name,
                  OrderDate = Ord.OrderDate
              }

    return Json(results);
}

This is an easier approach because I gain control and flexibility in exactly what values are returned in my Json response, I can ignore completely the buggy nature of the DataContractJsonSerializer and I’m serializing only the object parts I’m concerned with.

Retire IE6 – No More Excuses!

December 20th, 2009 Phil No comments
Elderly IE6

Elderly IE6

As sketchy details begin to emerge about Microsoft’s work on its latest version of Internet Explorer, the time has finally come for companies to prepare to dispose of IE6; the universally despised browser that has caused web developers the world over to cry out in despair for almost a full decade.

After originally being shipped with Windows XP and Windows Server 2003 in August 2001, it rose to the lofty heights of almost 90% market share at its peak in 2002 / 03.  However with such dominant market share, Microsoft had little incentive to innovate and the browser stagnated as more and more security holes were identified or introduced.

Read more…

10 Notable HTML5 Resources

December 5th, 2009 Phil No comments
The web's new golden child

The web's new golden child

Usually I’m not given to doing Letterman-style lists of topics, but I’m getting really interested and involved in HTML5 at the moment and there are a number of really good resources out there for those looking to learn more about this emerging specification.

  1. HTML5 Doctor (http://html5doctor.com) : has a raft of excellent articles relating to HTML5 and its semantics and how to use them.
  2. HTML5 Gallery (http://html5gallery.com) : is a showcase of some high-quality sites built using HTML5
  3. Techmic Screencasts (http://www.techmic.com) : is a great resource for quickly and easily learning cutting-edge web technologies, focusing on topics such as HTML5, Ajax, RDF, SVG, microformats, and web frameworks.
  4. Dive Into HTML5 (http://diveintohtml5.org/): is an incomplete, but useful introduction that “…seeks to elaborate on a hand-picked Selection of features from the HTML5 specification and other standards”.
  5. The HTML5 Specification (http://www.whatwg.org/html5) : is all the official technical documentation. Hardly light reading, but useful for an in-depth, specific treatment of each new feature.
  6. W3Schools HTML5 Reference (http://w3schools.com/html5/html5_reference.asp) : is a good alternative to the actual specification if you find that level of technical reading a bit overwhelming.
  7. HTML5 Shiv (http://ejohn.org/blog/html5-shiv) : There’s not much point getting too involved in HTML5 when IE doesn’t support most of it, right? This JavaScript technique shows an incredibly simple approach to overcoming that problem.
  8. Twitter (My HTML5 List) : has a huge community of professionals that can be tapped in to. Lots of links, resources and personal recommendations available.
  9. Your Community : There are plenty of great communities out there, full of enthusiastic, like-minded peers just ready to help you.
  10. You : Without the individual, the community is nothing. Once you get your head around the new surprises in HTML5, let other people know about it.

Got more suggestions? Leave a comment below or tweet them to @Phil_Wheeler.

Taking Advantage of HTML5 Today

November 28th, 2009 Phil 2 comments
The web's new golden child

The web's new golden child

I was asked in a formal situation recently, “If you were to build a new web site from scratch, which doctype would you use?”.

Me: “Commercial site for a customer?”

“Just a site for the open web”

“Well, then I guess I’d have to say <!doctype html>

I wish I had a camera for the look of shock and disbelief I was given in response.  But the fact of the matter is that for modern browsers, HTML5 is an excellent alternative for new sites and applications.

With the upcoming production release of Firefox 3.6 – and the inevitable hype that is surrounding it, I felt it was an opportune time to look at how the current mainstream browsers provide for the HTML5 specification.

Read more…

Deploying ASP.Net MVC Applications to Your Hosted Environment

October 18th, 2009 Phil No comments

I found myself in a very frustrating position last week as I tried to deploy my first ASP.Net MVC application to my own hosted web server.  If you’re building MVC apps for in-house use or for deployment to servers over which you have full control, you may have found the process to be quick, painless and generally quite enjoyable.  Similarly, if you’re deploying to servers running IIS7, then you may also have had a pretty good experience.

My hosting provider however, is running IIS6 and does not have configurations for MVC pre-prepared.  Customers need to raise a Tech Support ticket to request their site to be MVC-enabled on a case-by-case basis.  Not realising that I couldn’t just “build and drop”, I spent much time analysing my code and Web.Config before humbly going before the Tech Support folks and admitting I didn’t really know why my application wouldn’t run.

Here is a brief overview of the problems I encountered and what I had to do to overcome them.

Initial Deployment

I figured it was going to be a walk in the park after I read Phil Haack’s article on bin-deploying MVC applications.  However, after following his instructions to the letter and FTPing my files to my hosted server, I was greeted with an alarming and altogether unnatural-looking 404 page.  Well, that’s not right.  I pored over my Web.Config and controller classes to see what I could have done that wasn’t going to be picked up on my local machine.  Not much, as it turned out.  So in desperation, I swallowed my pride and logged a Tech Support ticket.

As it turned out, my host hadn’t installed Service Pack 1 for my account.  They did this almost immediately and I was miraculously presented with my app’s home page.  Success!

Or so I thought.  As soon as I’d closed the ticket as “resolved”, I browsed to a view page below the main home page and – horror – there it was again: that damn 404.

The Actual Problem

The full story of what my web host needed to do can be found on the ASP.Net MVC Learning page, tutorial 8.  The short of it is that I needed my hosting provider to create a wildcard script map for my account that would map all requests to the web server to the ASP.NET framework. That way, I could then use the default ASP.NET MVC route table with IIS 7.0 (in classic mode) or IIS 6.0 (which is what they were actually running).

Now the big, important “but”:

Be aware that this option causes IIS to intercept every request made against the web server. This includes requests for images, classic ASP pages, and HTML pages. Therefore, enabling a wildcard script map to ASP.NET does have performance implications.

[from the section, "Creating a Wildcard Script Map"]

What this meant was EVERY domain and subdomain I was running on my account was affected by this rule and each one that I did not want the rule applying for needed to be reconfigured individually.  This blog runs as a subdomain of my main account, so the WordPress PHP files found it all too much and my blog promptly died.

Hopefully if you find yourself in a similar situation to me, this will help you work through some of the gotchas involved in publishin MVC applications to older IIS boxes.

Working With Tables in jQuery

September 19th, 2009 Phil No comments

Possibly one of the most frustrating or confusing tasks a developer may find is retrieving information from within a table.  Getting references to cells, rows and columns often seems like it should be a doddle with jQuery, but getting just the right combination of selectors and commands can sometimes be more elusive than it would seem at first blush.

Let’s have a look at how to get the right information from your tables first time, every time.

Read more…

IE8 Developer Tools Need Love Too!

September 19th, 2009 Phil 3 comments

I attended a Microsoft Unplugged session the other day where Giorgio Sardo presented a discussion on creating cross-browser compatible websites using IE8’s Developer Tools and Expression Web SuperPreview. While I went in as a skeptical developer expecting to hear the usual rhetoric around some misguided enthusiasm about a new feature set that other browsers have been doing for years, I came out highly surprised and impressed with some of the tools that are bundled as part of the embattled browser.

Internet Explorer has a well-established track record of not performing. The legacy of IE6 still haunts web developers today and is widely loathed throughout that community, so it should come as no surprise to Microsoft that developers are cynical about any claims of “better performance”, “better standards” or “better tools”. Like most of my peers, I’m a devout Firebug enthusiast. It’s an excellent tool for playing with your styles and markup and quickly visualising your DOM element dimensions. I’ve always felt that IE8’s developer tools never really measured up in this regard. But the IE8 has its own little bag of tricks that present a good argument against dismissing the browser completely.

I’m going to look at some of the more interesting and useful features in future posts, but I’ll quickly cover off a couple now. The first two are found in the Tools menu.

Start by opening up the IE8 Developer Tools by pressing F12 and have a look at the Tools menu. You will see three submenus: Resize >, Show Ruler and Show Color Picker. The Ruler is really useful if you want to measure out page elements (image heights, content block widths, etc). You can select from one of four high-contrast colours, easily snap to page elements, draw multiple rulers on the page and generally measure anything you want, however you want. Compare this to Firefox’s MeasureIt addon which, for starters, is an addon (as opposed to baked-in), and – at time of writing – was basically restricted to a single box outline with fixed ruler tickers. Ultimately, they’re two very basic features and they both do what they’re designed to do, but it’s the little features that make the difference.

The color picker is in a similar vein, except here Firefox has the advantage. I didn’t even know that IE8 had a color picker and have always used the ColorZilla addon instead. Both tools allow you to sample the color of a page, but the Firefox variant adds a lot of extra functionality such as being able to take your chosen color and change its RGB values as well as the Webpage DOM Color Analyzer (didn’t know about that one?! Try it now. Right-click and select Webpage DOM Color Analyzer).

In upcoming posts, I’ll look at some other lesser-known features of the Developer Tools, including script debugging and page optimisation.

Practical Applications for the jQuery Data() Function

September 15th, 2009 Phil No comments

In one of my previous posts, I looked at some of the lesser known and understood features of the jQuery library. Included among them was the data() function, which allows you to set and get values at a named point associated with a DOM element.  An interesting feature, but not one that’s documented particularly extensively on the jQuery site.  So in this post, I’d like to look at this in a bit more depth and see what we can really do with it.

Read more…