latest news
Getting Over Your jQuery DOM Ready Addiction
If you’re getting started with jQuery or have been using casually for some time, you’ll have read your share of blogs, documentation and assorted other sources decreeing that any and all jQuery code must be declared within the following code:
<script type=”text/javascript”>
jquery(document).ready(function(){
// your code goes here…
});
</script>
This isn’t strictly bad practice per se. If you want your events bound to your DOM elements correctly, you’re generally best to ensure that the DOM is fully loaded first. However this blanket, unquestioning approach doesn’t mean you’re adopting good practice all the time either. Here’s why.
Read the rest of this entry »
Event Binding with jQuery delegate()
jQuery version 1.4.2 was released on February 19th this year and along for the ride is the new jQuery.delegate() method. This method is very similar to the $.live() method in that it is used to:
Attach a handler to the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.
So what exactly is the big deal and how is it different to $.live()? In this post I’ll look at the two side-by-side and demonstrate why $.delegate() opens up some new doors that may make you decide to let $.live() $.die().
Read the rest of this entry »
Ajax Gotchas with jQuery and ASP.Net MVC
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 the rest of this entry »
Quick Hits – jQuery.Map()
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
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!
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.
10 Notable HTML5 Resources
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.
- HTML5 Doctor (http://html5doctor.com) : has a raft of excellent articles relating to HTML5 and its semantics and how to use them.
- HTML5 Gallery (http://html5gallery.com) : is a showcase of some high-quality sites built using HTML5
- 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.
- 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”.
- 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.
- 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.
- 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.
- Twitter (My HTML5 List) : has a huge community of professionals that can be tapped in to. Lots of links, resources and personal recommendations available.
- Your Community : There are plenty of great communities out there, full of enthusiastic, like-minded peers just ready to help you.
- 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
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 the rest of this entry »
Deploying ASP.Net MVC Applications to Your Hosted Environment
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.



