In this article we will be looking at a different type of architecture. One in which we utilize jQuery's ability toeasily transfer data (via Ajax and JSON) from the client to the server. We then use ASP.NET and LINQ to SQL to query the database and return a collection of data which gets (automatically) serialized to JSON and sent to the client. The benefits of combining these technologies include: more responsive applications, more processing on the client, less processing on the server and reduced network traffic. Everything runs faster and uses fewer resources.
Still not convinced? Here are some additional benefits of this architecture:
Benefits of the Architecture
- Unlike an ASP.NET UpdatePanel we only pass what we need; we only receive what we need. We don’t pass ViewStates, in fact we don’t even have a ViewState. We also don’t pass entire HTML chunks and receive HTML chunks we don’t use. For more on this; read: Why ASP.NET AJAX UpdatePanels are dangerous.
- By using jQuery to call the web service directly, we’ve eliminated over 100 KB of JavaScript and three extra HTTP requests that's included when you use ASP.NET Ajax.
- Less dependencies – because all our code is simply xHTML we could switch to a PHP or a Java backend and none of our code for the UI would have to change. That's right, there are no server-controls; that means no GridViews, no Repeaters, no ListViews, nothing that uses runat server will be found on the page. Not even a ScriptManager.
- Usability – We can create RIA interfaces AND maintain usability, giving us the best of both worlds.
- Cross-Browser friendly – We use nothing but xHTML code and jQuery which works across browsers.
- The entire presentation for the UI is done via CSS. Change the CSS and the entire UI can look different.
- We maintain a 'Separation of Concerns' - this means we have 3 distinct and wholly separate code bases. A content or HTML level. A presentation or CSS level and a behavior or JavaScript level. We don't have code mixed together in a web-page jambalaya.
- Switching architectures from Web Forms to MVC is a breeze.
Hopefully you are salivating at these benefits enough to decide to get your feet wet and follow along.
In this article will be leveraging these technologies to build a grid (or what looks like a table). Later on, in future articles, I will then show you how to implement sorting, paging and filtering on the grid. I have divided this article up into four sections: 1. Sever-side code (ASP.NET). 2. HTML 3. jQuery and lastly CSS.
ASP.NET
In this article I will be using LINQ to SQL to query the database and return a collection. LINQ to SQL allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update, insert and delete data from it. LINQ to SQL fully supports transactions, views, and stored procedures. If you're not familiar with LINQ then I will refer you to these articles: Using LINQ to SQL (Part 1) and LINQ to SQL - 5 Minute Overview.
The goal of this article is not to teach you LINQ. But I will say that if you are not using LINQ and you are still using a DataReader or DataSet to access your data then shame on you. Simply put, I believe LINQ is the coolest technology Microsoft has come out with in recent years.
And the best news is, it's EASY to use. Let's look at the code:
C#:
- public class CourseReservations
- {
- public long CourseId { get; set; }
- public string Course { get; set; }
- public string Time { get; set; }
- public int Holes { get; set; }
- public int Golfers { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- }
- [WebMethod]
- public List<CourseReservations> GetGolfCourseReservations()
- {
- using (DataContext dc = new DataContext())
- {
- var query = from res in dc.GolfReservations
- where res.CourseId == 1
- select new CourseReservations
- {
- CourseId = res.CourseId,
- Course = res.GolfCourse.CourseName,
- Time = res.DataAndTime.ToShortTimeString(),
- Holes = res.Holes,
- Golfers = res.Golfers,
- FirstName = res.Aspnet_User.GolfUser.FirstName,
- LastName = res.Aspnet_User.GolfUser.LastName,
- };
- return query.ToList();
- }
- }
The first thing we do is create a class called CourseReservations. This class contains all the properties we will need to create our grid on the client. In other words, these will become our columns. The next part is our LINQ statement. This code uses LINQ query syntax to retrieve a sequence of GolfReservations for a given course. Note how the code is querying across the GolfReservations / GolfCourse / Aspnet_User / GolfUser relationships to retrieve all the data we need from our tables, and we didn't have to write any SQL filled with JOINS to do it.
We then return a list of CourseReservations. What's important to note is that our list will get automaticallyserialized to JSON. How fantastic is that? Before we move on, also note the name of our method:GetGolfCourseReservations(). This is what we will call via Ajax using jQuery.
HTML
HTML:
- <ul id="reservationsList" class="stripedList"></ul>
That's right, just a simple unordered list with an id of "reservationsList" and class of "stripedList". We don't use any controls, nothing with runat="server" will be found on the page. This way we don't have any ViewState taking up load time, nor do we have Microsoft inserting JavaScript into our page without our consent. Our page, at least on the front-end, is devoid of ASP.NET or any other language. Nothing but pure HTML. If we ever have to port to PHP or JSP we wouldn't have to change a single thing on the UI side.
jQuery
Let's look at the jQuery code now. Bit by bit.
JAVASCRIPT:
- //Ajax
- function SendAjax(urlMethod, jsonData, returnFunction) {
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: urlMethod,
- data: jsonData,
- dataType: "json",
- success: function(msg) {
- // Do something interesting here.
- if (msg != null) {
- returnFunction(msg);
- }
- },
- error: function(xhr, status, error) {
- // Boil the ASP.NET AJAX error down to JSON.
- var err = eval("(" + xhr.responseText + ")");
- // Display the specific error raised by the server
- alert(err.Message);
- }
- });
- }
Notice the SendAjax() method's signature. It takes three parameters, the first urlMethod is the path to the Web Service followed by the name of the Web Method. It should look something like "webservice.asmx/webmethod". The second parameter jsonData will be exactly that, your JSON data. More on this later. The final parameter returnFunction will be the function you wish to call after the return trip from the server.
The $.ajax() method performs an asynchronous HTTP (Ajax) request. You can read all about it here, but for now, just know it's the liaison for the client / server relationship; or the Ajax call.
We will use this light, but powerful SendAjax() method over and over again each time we wish to go to the server.
JAVASCRIPT:
- //Stripe the rows
- function StripeRows(list) {
- $(list).find('li').removeClass('evenRow');
- $(list).find('li:even').addClass('evenRow');
- }
This function is simply used to stripe the rows. Every other row will be colored differently in our grid. You pass it a list, it then finds all the list items in that list and removes a class. It then adds a class to all the even list items. The reason why I removeClass() from all list items first is so that if you ever add or remove list items (dynamically) to the grid you don't get them all messed up colorwise.
JAVASCRIPT:
- //This fires when the DOM is ready
- //So this starts the ball rolling...
- $(document).ready(function() {
- GetGolfCourseReservations();
- });
If you are new to jQuery then you need to start by understanding $(document).ready(). You can read all about it here. But the bottom line is that everything inside this method will load as soon as the DOM is loaded and before the page contents are loaded. This is extremely efficient because we don't have to wait for images or content to load, just the DOM elements. Again, if you are new to jQuery start by understanding the $(document).ready() method.
We are telling it to call the method GetGolfCourseReservations() as soon as browserly possible.
JAVASCRIPT:
- function GetGolfCourseReservations()
- {
- //Ajax
- var urlMethod = "ws_Reservations.asmx/GetGolfCourseReservations";
- var jsonData = '{}';
- SendAjax(urlMethod, jsonData, ReturnGetGolfCourseReservations);
- }
- function ReturnGetGolfCourseReservations(msg) {
- var listItems = "";
- $.each(msg.d, function(key, val) {
- listItems += "<li>" +
- "<span class='c1'>" + val.Time + "</span>" +
- "<span class='c2'>" + val.FirstName + "</span>" +
- "<span class='c2'>" + val.LastName + "</span>" +
- "<span class='c3'>" + val.Course + "</span>" +
- "<span class='c4'>" + val.Holes + "</span>" +
- "<span class='c4 cLast'>" + val.Golfers + "</span>" +
- "</li>";
- }
- );
- $("#reservationsList").html(listItems);
- StripeRows('#reservationsList');
- }
The three lines in the GetGolfCourseReservations() method will become very familiar to you in this methodology. Recall that urlMethod is the path to your web service and your web method. You do remember our .asmx file contains a web method called GetGolfCourseReservations? Good. The next line with jsonData is the JSON that we are passing in. Note that if you are not passing any data, as we are in this case, you must still have the empty curly brackets. Finally, the third line is our call to SendAjax() method. Notice the third parameter: ReturnGetGolfCourseReservations. This is the method to be called on the round trip from the server. Conveniently you will find this function one line down. I always keep to this standard.
In our ReturnGetGolfCourseReservations method we loop through the returned JSON and create our rows or list items. We then drop our list items into our unordered list and lastly call our method to strip the rows.
TIP: Two tools that are indispensable for this methodology are Firebug and this JSON checker. Without Firebug you will not get far. It allows you to see all your Ajax calls, the post, the request and the returned JSON. Get it and learn it.
CSS
Lastly, let's look at the CSS involved to make our grid look pretty. Do note that we could have used a table instead of a list very easily. It's your choice.
CSS:
- <style type="text/css">
- #reservationsList {width:500px; max-height:600px; background:#fff; overflow:auto;}
- /*STRIPE LIST*/
- ul.stripedList {
- margin:0;
- padding:0;
- list-style:none;
- }
- .stripedList li {
- display:block;
- text-decoration:none;
- color:#333;
- font-family:Arial,Helvetica,sans-serif;
- font-size:12px;
- line-height:20px;
- height:20px;
- }
- .stripedList li span {
- display:inline-block;
- border-right:1px solid #ccc;
- overflow:hidden;
- text-overflow:ellipsis;
- padding:0 10px;
- height:20px;
- }
- .stripedList .evenRow {background:#f2f2f2;}
- .c1 {width:55px;}
- .c2 {width:70px;}
- .c3 {width:130px;}
- .c4 {width:15px;}
- .cLast {border:0 !important;}
- </style>
Most of the CSS is pretty straight forward; we stylize our list-items and use spans as our cells. The classes .c1, .c2 ect. allow us to assign a width to each column.
The Take Away
What I really want you to take away from this article is all the benefits gathered from this methodology. When I build Web-based apps the thing at the front of my mind is speed. It's all about speed. Nobody likes to wait for anything these days, on the web or off. This is about as fast as you can do things. In addition, we have nice clean code that adheres to the separation-of-concerns. On the front is just good old HTML, probably the first thing you learned when creating websites. On the back-end is our Web Service that does our actionable request: get, save, update and delete. That's all it does, it knows nothing about the UI, unlike a typical ASP.NET page with its CodeBehind page that is all aware of the UI and talks to it. If we ever had to change over to an Apache server and use PHP we wouldn't have to change a thing on the front-end, simply our methods on the back-end would change.
We allow our CSS file to control the way the entire application looks. Once again, compare this to many typical ASP.NET apps that use Web Controls and want you to set presentation properties either in the .aspx page or the CodeBehind page. Yuck. Never do that.
Lastly, not only is our code fast and clean, but it's also lean. When you get good at this methodology there is usually a lot less code. Less code is always a good thing.