Using ASP.NET Wep API and jQuery

Limited by some ancient technology (VS2005 and IE6), I was working a developer on Friday to bring some client-side calls to a web application. We needed to kick off a long-running process. So, instead of having the the web page spin and be unresponsive for 6+ minutes, we opted to use an .asmx service and use jQuery to connect with that service to show the current status. As it turned out, IE6 doesn’t properly work with JSON, so we ultimately just exposed some strings and some POX.

That got me thinking, what is the state-of-the-art for since sort of thing, nowadays? I’ve done some “Hello, world!” type things with Web API, but is that the way to do things? I decided to whip up some code to find out. That turned into many, many hours – and I’m really sad with what I discovered.

Dynamic “this” and dynamic “that” – for everyone!:
I know, I know. All the cool kids want EVERYTHING to be dynamic. We want dynamic languages and dynamic databases. You could call me a grumpy-old-man, but this is such a tragic, tragic trend. There is a reason why things are explicit. Explicitness removes assumptions. I’ve said for decades now: “Assumptions are at the root of ALL software bugs”. For example: “I assumed that wouldn’t be null.”, “I assumed that this would have a .FirstName property”, or “I assumed this wouldn’t throw an exception”. It’s almost as if the whole development community said “Finally, now we’re able to rise above static typing and structure!” – as if it were a bad thing? But is it a bad thing?

Well, I spent HOURS today debugging JavaScript because the JSON object I was getting back wasn’t what I thought it should be. I assumed it was one way – and it wasn’t. There was no compiler or tool that could “enforce” either my assumption – or what the language asserted. So, me, the sucker-developer is left wasting hours trying to do what a compiler does, naturally.

You can blame that on a inexperienced developer or you can blame it on the tooling… or, dare I say it, you can blame the wacky-world of dynamic (or in the case of JavaScript – weak typing).

Here’s the problem though – look around, EVERYONE is building their apps, their careers, and even their businesses on JavaScript. This, in my professional opinion, is madness. I understand why, but we, as technology professionals should’ve corrected this much earlier on. Someone, at some point should have said “Sheesh, JavaScript is a REALLY horrible language. If we’re going to continue on, we should really replace it or at least overhaul it”. Alas, we didn’t. Now, we’re all pretty screwed – because JavaScript really is a horrible language.

Enough of my whining! I’m just sad and frustrated that THIS is the best we could evolve to, in the year 2013. As a developer, dynamic typing and weak-typing specifically, wastes my time, makes me less efficient and forces me to produce lower-quality software. And that, is frustrating and annoying – because it doesn’t have to be this way.

Setting up a Web API “service”:
OK, so we want to have some client-side code talk with the server-side. Although we could use MVC controller actions for this, Microsoft has produced Web API. This is basically a RESTful framework which works similar to MVC controllers, but is specifically designed for application consumers. It can automatically produce JSON or XML, depending on what you asked for – and it’s pretty easy to work with.

Considering that the return from these service calls is going to be JSON or XML, they need to have some structure. For example: { “Name” : “John” } or <name>John</name> – right? So, that means that I really need to return a data structure from each of these calls – even if that data structure only has one method. That’s what I did:

image

So, I create a Web API controller:

image

I create a new action, and set the return type to be my custom data structure:

image

I know, you’re going to say: “Hey dum-dum, why not just return a DateTime object and let the client-do the formatting?”. This, was one of the stupid things I spend OVER and hour on. I found tons of examples of people that use Date.js for formatting a date, but for the life of me I could not get it working. Instead, it would just format the date in the full ISO8601 format.

Ok – so we have a Web API controller action that returns a data structure. Should be simple, we call /api/SampleWebApi/GetTime and in JavaScript, we should be able to output the .Text property of what comes back.

Use jQuery to call a service:
At this point, we have a service set up, we just need to call it and do something with the result. Here’s all that is needed:

image

We include a reference to jQuery of course, with the <script> tag. Next, we create a <div>, which is where we will put the result (the current date/time).

If you are not familiar with jQuery, let me see if I can summarize the code above:

  • $().ready(func) – is a function call that executes “func” (an inline, anonymous function – like above, or a named-function) when the page is loaded (technically, when the DOM is loaded).
  • $(“#statusLabel”) – is a jQuery “selector” which goes and selects anything with an id (designated by the “#” selector option) of “statusLabel”.
  • setInternal(func, delay) – a built-in JavaScript function to run code (func) every so-many (delay) milliseconds.
  • .getJson – this is a convenience function from jQuery that will call the specified service and put the return value inside of “data”. We then read data.Text and put that in the div.

How does JavaScript know we have a .Text property? It doesn’t. This is part of that dynamic-typing/weak-typing that I mentioned before. If it’s not there or typoed at run-time, you get a run-time error.

Summary:
As you can see, this is pretty simple to set up both on the server side and client-side. I started running into many more problems when I started to bring back more complex objects and wanted to do more formatting on the client-side.

For this reason, in MVC for example, I’m still very much a fan of an MVC controller returning a pre-formatted partial view instead of returning JSON and doing client-side formatting. If I create a partial view in MVC, I have the benefit of a designer, and intellisense for the data structure with which I’m working.

The opposite approach would be to offer that raw data via a service, use jQuery to get it and use a variety of scripts and techniques to format it. I have found that arena to be very difficult. There are no consistent products, everything is buggy (because of the dynamic and weak typing).

So, in my opinion, this sort of JSON/XML service + jQuery has it’s place, but in most cases, I will opt to see if I can do the formatting and layout on the server-side first. The tooling and error messages are much better!

Posted in ASP.NET, ASP.NET MVC, JQuery, Uncategorized, WCF, Web Services, XML stuff

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 5 other followers

%d bloggers like this: