Photo Gallery – jQuery Release

My initial goal of using jQuery was to leverage the library to enhance the photo gallery user experience. Along the way, I decided to use AJAX to remove all page post backs (except the first one of course). So now my code behind looks like this:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

In addition to having no event handlers in the page controller, the following changes have been made:

  • The aspx page is not using any controls that have a runat=’server’ attribute. The exception for this is that I am still using an ASP.NET Master Page. This could easily be removed, however I would like to possibly expand the photo gallery with additional pages and want to leverage a common header / footer.
  • My JavaScript is embedded using HTML script tags and not the ASP.NET ScriptManager. This stops the MS AJAX library wrappers around the web service calls and base library from being injected into the browser.

I pushed all the code that used to be in the page controller to a windows service (asmx) page that is called via jQuery AJAX calls. For instance here is the shell for the login web service that resides in a “ServiceLayer.asmx” file:

[WebMethod(EnableSession = true)]
public string Login(string userName, string passWord)
{
 // ... code goes here ...
}

This is called using jQuery in the following manner:

function DoLogin()
{
    var userName = $("#userName").val();
    var passWord = $("#passWord").val();
    HideLogin();
    attempt++;
    $.ajax({
        type: "POST",
        url: "ServiceLayer.asmx/Login",
        data: "{userName:'" + userName + "',passWord:'" + passWord + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(msg){OnFailed(msg.d);},
        success: function(msg){OnSucceedSecurity(msg.d);}
    });
}

The ‘$.ajax’ jQuery wrapper hides the complexity of the AJAX call and ensures better cross-browser compliance. Here is a great article by David Ward on how to use jQuery to call ASP.NET web services. The ‘url’ value contains the path to the web service. The ‘data’ value holds the parameters to be passed into the web service. Notice that the name part of the name/value pairs in the ‘data’ value must match the parameter names in the web service.

The source code for this version of the photo gallery can be found here. To get this code working, put some photos in the “Photos” folder. A working version of this code can be found here.

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

*