blog.dogma.co.uk

Thursday, 19 August 2010

jQuery Remote Validation with ASP.NET MVC

Note: When I say ASP.NET MVC, this post only applies to version 2 and above, which at the time of writing includes MVC3 Preview 1.

There is a bit of client-side magic that happens on some forms these days. You’ve probably seen it; you type in a username or an email address into a registration form and before you have finished entering the next field, the form is already telling you whether or not the username/email address has already been used. Or, maybe you’ve typed in a gift code that immediately validates (or not).

This magic, contrary to the belief of some posse’s of some Faygo wielding clowns, is not magic but a technique called “remote validation”. Remote Validation is providing validation on the client (using something like JavaScript, Flash or Silverlight) that can utilise server side logic by way of an Ajax request. In most cases, validating the input against your data store.

At this point it should be noted that I will be focusing on an implementation that relies on the jQuery Validation plug-in. If you would prefer to use the MSAJAX library, I will now point you to Brad Wilson’s excellent post on the subject. My implementation is based on Brad’s, with a few differences, that I’ll mention on the way.

Okay to the implementation. As with a lot of things, jQuery makes our lives a lot easier. I expect John Resig should at least take some credit for my steady marital status, I’m not getting complacent. jQuery offers a plug-in, one of not very many officially supported plug-ins, called jQuery Validate. I am sure you are already acquainted. The validation plug-in offers remote validation out of the box, the implementation is both incredibly simple and efficient. Below is an example borrowed (I’m not giving it back) from the jQuery documentation.

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: "check-email.php"
    }
  }
});

The above example says three things about the field called email.

  1. It’s required.
  2. It’s and email address.
  3. As an extra check, the browser should pass the email address to an endpoint called “check-email.php”.

The remote endpoint has but one job, to return true or false (as a JSON object). It is up to you how that decision is arrived at. By default, this check is made either when the field loses focus or before the form is submitted.

That is fantastic if you can be bothered to write all of a long sentence each time, yeah I have better things to do like try and learn Japanese and the Ukulele simultaneously. Yeah, that’s how I roll, yo.

What we need to do is bake in some ASP.NET MVC wizardry. I have loved data annotations, since I first saw them in that scaffolding thing, umm Dynamic Data. Just awesome, one day I’d like to build a website with just a long string of attributes.

Okay, I’m going to assume that you are already familiar with how Html.EnableClientValidation() works for jQuery for the rest of this post. If there is any call for it, I focus on this on another post.

That assumed, we need to create a new Attribute to flag our property with. Our use case scenario will be a basic registration form (very basic) that requires a username, that has not already been used. Our model is below:

using System.ComponentModel.DataAnnotations;

public class Reg {
	[HiddenInput(DisplayValue = false)]
	public int ID { get; set; }

	[StringLength(50), Required]
	public string Name { get; set; }

	[StringLength(250), Required]
	public string Email { get; set; }
}

So our form is going to require a name and an email with maximum string lengths. Lets create an Attribute that says check me against something remote:

using System;
using System.ComponentModel.DataAnnotations;
using System.Configuration;

[AttributeUsage(AttributeTargets.Property)]
public class RemoteAttribute : ValidationAttribute {
	#region Properties
	public string Key { get; set; }
	public string[] AdditionalProperties { get; set; }
	#endregion

	#region Methods
	public virtual string GetUrl() {
		return ConfigurationManager.AppSettings[Key];
	}

	public override bool IsValid(object value) {
		return true;
	}
	#endregion
}

The key difference between mine and Brad’s Remote Attribute, is the way the remote URL is retrieved. Brad’s URL is baked straight into the Attribute, whereas mine is takes the URL from a Web Config AppSetting. I made this change because I tend to reuse models between projects and didn’t want my routing to be dictated to by my model. In the future I would like to have the option to set the URL in the Global.asax, so I can make use of T4MVC’s strongly typed ActionResults.

I have also added a string array called AdditionalProperties, this will contain a list of additional properties that I also want to pass to the remote endpoint. This is useful if you don’t want to invalidate an email address on a registration, because it already exists on the registration you’re currently editing. I’m going to infer my parameter name from the property.

If you haven’t read Brad’s post, I should mention that we’re returning true in IsValid() because this Attribute will not be performing traditional server-side validation. This is not because I’m lazy, but rather because we don’t know what that validation will be until it is implemented. I am quite lazy.

We’re also going to need an Adapter. An Adapter tells the compiler how to pass the Attribute to the client. Here it is:

using System.Collections.Generic;
using System.Web.Mvc;

public class RemoteAttributeAdapter : DataAnnotationsModelValidator<RemoteAttribute> {
	public RemoteAttributeAdapter(ModelMetadata metadata, ControllerContext context, RemoteAttribute attribute) : base(metadata, context, attribute) { }

	public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
		var rule = new ModelClientValidationRule {
			ErrorMessage = ErrorMessage,
			ValidationType = "remote"
		};

		rule.ValidationParameters["url"] = Attribute.GetUrl();
		rule.ValidationParameters["type"] = "post";
		rule.ValidationParameters["additionalProperties"] = Attribute.AdditionalProperties; ;

		return new[] { rule };
	}
}

For the most part this Adapter is just pairing up my attribute’s properties with the parameter’s of the jQuery validation plug-in. The only property that isn’t like for like at this stage is the additionalParameters parameter, this will map to a jQuery parameter called data.

Note: I’ve also hardcoded that the request be a POST. Bad practice, possibly, but I can’t see a call of this nature legitimately being a GET. I am posting information for comparison, not to specifically get information. You may have your own take on this, in which case you are free to adjust your implementation.

Which brings to the second example provided by the jQuery documentation:

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "check-email.php",
        type: "post",
        data: {
          username: function() {
            return $("#username").val();
          }
        }
      }
    }
  }
});

In the example, additional parameters are sent to the endpoint to add context to the validation method. I will replicate this in my client-side validation. My client-side validation will not be reinventing the wheel, I will be building on the file called MicrosoftMvcJQueryValidation.js. This file was originally provided in some of the preview releases of ASP.NET MVC2, and I can now never bloody find, so will include the script in it’s entirety at the bottom of this post. For now though, lets look at the additions I have made:

function __MVC_ApplyValidator_Remote(object, validationParameters, fieldName) {
	var obj = object["remote"] = {};
	var props = validationParameters.additionalProperties;

	obj["url"] = validationParameters.url;
	obj["type"] = validationParameters.type;

	obj["beforeSend"] = function () {
		var elementName = fieldName + "_validationMessage";
		$("#" + elementName).addClass("remote");
	};

	obj["complete"] = function () {
		var elementName = fieldName + "_validationMessage";
		$("#" + elementName).removeClass("remote");
	};

	if (props) {
		var data = {};

		for (var i = 0, l = props.length; i < l; ++i) {
			var param = props[i];
			data[props[i]] = function () {
				return $("#" + param).val();
			}
		}

		obj["data"] = data;
	}
}

The above block of code is added at around line 32, and maps the ASP.NET MVC generated JS to a jQuery Validate object. In additional to what you might have been expecting, I have also bound to two event handlers. This allows me to provide field by field loading indications the user “Hey user, I’m doing something clever to this field.” I do this in addition to ajaxStart and ajaxStop.

If you focus in on the for statement, you’ll see that I’m iterating through the additionalParameters array to produce a data parameter exactly the same in function as in the second  jQuery example.

Let’s look at the second addition I’ve made:

// Line 110
function __MVC_CreateRulesForField(validationField, fieldName) {

// Line 137
			case "remote":
				__MVC_ApplyValidator_Remote(rulesObj, thisRule.ValidationParameters, fieldName);
				break;

// Line 156
		rulesObj[fieldName] = __MVC_CreateRulesForField(validationField, fieldName);

In the addition above I am simply adding an extra case into the switch that determines which adapter method to fire. This was necessary because I require the field name to be passed to the adapter.

Right, we’re almost there. Just four more steps:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RemoteAttribute), typeof(RemoteAttributeAdapter));

Step One: Add the above line of code to the Application_Start method of your Global.asax.

using System.ComponentModel.DataAnnotations;

public class Reg {
	[HiddenInput(DisplayValue = false)]
	public int ID { get; set; }

	[StringLength(50), Required, Remote(Key = "name-test", AdditionalProperties = new[] { "ID" })]
	public string Name { get; set; }

	[StringLength(250), Required]
	public string Email { get; set; }
}

Step Two: Adjust our model to include the new RemoteAttribute. I’m telling the attribute to look for an AppSetting of “name-test” in web.config.

<add key="name-test" value="/Home/NameTest"/>

Step Three: Add an AppSetting called “name-test” to your web.config.

public virtual ActionResult NameTest() {
	return Json(true);
}

Step Four: If you have not already done so, create your end point.

Discussing the creation of the form is beyond the scope of this post, mainly because it is dead easy and would sit better in a general post about jQuery validation with ASP.NET MVC. I will clarify that you need to reference jQuery and jQuery Validate. You will also need to add Html.EnableClientValidation() to the top of your form.

So what have we done here. We have created an Attribute and an AttributeAdapter pair that will allow you to describe a remote interaction between the server and your model. We have registered this Attribute/Adapter pair in our Global.asax file, so ASP.NET knows to look out for it. We have then transformed the interaction into a state that jQuery can the use using our modified MicrosoftMvcJQueryValidation.js file.

The complete MicrosoftMvcJQueryValidation.js source as promised:

/// <reference path="jquery-1.3.2.js" />
/// <reference path="jquery.validate.js" />

// register custom jQuery methods

jQuery.validator.addMethod("regex", function (value, element, params) {
	if (this.optional(element)) {
		return true;
	}

	var match = new RegExp(params).exec(value);
	return (match && (match.index == 0) && (match[0].length == value.length));
});

// glue

function __MVC_ApplyValidator_Range(object, min, max) {
	object["range"] = [min, max];
}

function __MVC_ApplyValidator_RegularExpression(object, pattern) {
	object["regex"] = pattern;
}

function __MVC_ApplyValidator_Required(object) {
	object["required"] = true;
}

function __MVC_ApplyValidator_StringLength(object, maxLength) {
	object["maxlength"] = maxLength;
}

function __MVC_ApplyValidator_Remote(object, validationParameters, fieldName) {
	var obj = object["remote"] = {};
	var props = validationParameters.additionalProperties;

	obj["url"] = validationParameters.url;
	obj["type"] = validationParameters.type;

	obj["beforeSend"] = function () {
		var elementName = fieldName + "_validationMessage";
		$("#" + elementName).addClass("remote");
	};

	obj["complete"] = function () {
		var elementName = fieldName + "_validationMessage";
		$("#" + elementName).removeClass("remote");
	};

	if (props) {
		var data = {};

		for (var i = 0, l = props.length; i < l; ++i) {
			var param = props[i];
			data[props[i]] = function () {
				return $("#" + param).val();
			}
		}

		obj["data"] = data;
	}
}

function __MVC_ApplyValidator_Unknown(object, validationType, validationParameters) {
	object[validationType] = validationParameters;
}

function __MVC_CreateFieldToValidationMessageMapping(validationFields) {
	var mapping = {};

	for (var i = 0; i < validationFields.length; i++) {
		var thisField = validationFields[i];
		mapping[thisField.FieldName] = "#" + thisField.ValidationMessageId;
	}

	return mapping;
}

function __MVC_CreateErrorMessagesObject(validationFields) {
	var messagesObj = {};

	for (var i = 0; i < validationFields.length; i++) {
		var thisField = validationFields[i];
		var thisFieldMessages = {};
		messagesObj[thisField.FieldName] = thisFieldMessages;
		var validationRules = thisField.ValidationRules;

		for (var j = 0; j < validationRules.length; j++) {
			var thisRule = validationRules[j];
			if (thisRule.ErrorMessage) {
				var jQueryValidationType = thisRule.ValidationType;
				switch (thisRule.ValidationType) {
					case "regularExpression":
						jQueryValidationType = "regex";
						break;

					case "stringLength":
						jQueryValidationType = "maxlength";
						break;
				}

				thisFieldMessages[jQueryValidationType] = thisRule.ErrorMessage;
			}
		}
	}

	return messagesObj;
}

function __MVC_CreateRulesForField(validationField, fieldName) {
	var validationRules = validationField.ValidationRules;

	// hook each rule into jquery
	var rulesObj = {};
	for (var i = 0; i < validationRules.length; i++) {
		var thisRule = validationRules[i];
		switch (thisRule.ValidationType) {
			case "range":
				__MVC_ApplyValidator_Range(rulesObj,
                    thisRule.ValidationParameters["minimum"], thisRule.ValidationParameters["maximum"]);
				break;

			case "regularExpression":
				__MVC_ApplyValidator_RegularExpression(rulesObj,
                    thisRule.ValidationParameters["pattern"]);
				break;

			case "required":
				__MVC_ApplyValidator_Required(rulesObj);
				break;

			case "stringLength":
				__MVC_ApplyValidator_StringLength(rulesObj,
                    thisRule.ValidationParameters["maximumLength"]);
				break;

			case "remote":
				__MVC_ApplyValidator_Remote(rulesObj, thisRule.ValidationParameters, fieldName);
				break;

			default:
				__MVC_ApplyValidator_Unknown(rulesObj,
                    thisRule.ValidationType, thisRule.ValidationParameters);
				break;
		}
	}

	return rulesObj;
}

function __MVC_CreateValidationOptions(validationFields) {
	var rulesObj = {};
	for (var i = 0; i < validationFields.length; i++) {
		var validationField = validationFields[i];
		var fieldName = validationField.FieldName;
		rulesObj[fieldName] = __MVC_CreateRulesForField(validationField, fieldName);
	}

	return rulesObj;
}

function __MVC_EnableClientValidation(validationContext) {
	// this represents the form containing elements to be validated
	var theForm = $("#" + validationContext.FormId);

	var fields = validationContext.Fields;
	var rulesObj = __MVC_CreateValidationOptions(fields);
	var fieldToMessageMappings = __MVC_CreateFieldToValidationMessageMapping(fields);
	var errorMessagesObj = __MVC_CreateErrorMessagesObject(fields);

	var options = {
		errorClass: "input-validation-error",
		errorElement: "span",
		errorPlacement: function (error, element) {
			var messageSpan = fieldToMessageMappings[element.attr("name")];
			$(messageSpan).empty();
			$(messageSpan).removeClass("field-validation-valid field-validation-isvalid");
			$(messageSpan).addClass("field-validation-error");
			error.removeClass("input-validation-error");
			error.attr("_for_validation_message", messageSpan);
			error.appendTo(messageSpan);
		},
		messages: errorMessagesObj,
		rules: rulesObj,
		success: function (label) {
			var messageSpan = $(label.attr("_for_validation_message"));
			$(messageSpan).empty();
			$(messageSpan).addClass("field-validation-valid field-validation-isvalid");
			$(messageSpan).removeClass("field-validation-error");
		}
	};

	// register callbacks with our AJAX system
	var formElement = document.getElementById(validationContext.FormId);
	var registeredValidatorCallbacks = formElement.validationCallbacks;
	if (!registeredValidatorCallbacks) {
		registeredValidatorCallbacks = [];
		formElement.validationCallbacks = registeredValidatorCallbacks;
	}
	registeredValidatorCallbacks.push(function () {
		theForm.validate();
		return theForm.valid();
	});

	theForm.validate(options);
}

// need to wait for the document to signal that it is ready
$(document).ready(function () {
	var allFormOptions = window.mvcClientValidationMetadata;
	if (allFormOptions) {
		while (allFormOptions.length > 0) {
			var thisFormOptions = allFormOptions.pop();
			__MVC_EnableClientValidation(thisFormOptions);
		}
	}
});

Tuesday, 13 July 2010

Request.IsAjaxRequest()

Hi,

This is just a quick post to explain how Request.IsAjaxRequest() knows that a request sent to the server is an Ajax request rather than a traditional browser request.

First of all though, what is an Ajax request? Well strictly speaking, the X in the acronym AJAX stands for XMLHttpRequest. XMLHttpRequest is an object, created by Microsoft at the turn of the century, which allows the sending of HTTP requests using JavaScript (the J). The acronym was first coined by Jesse Garrett in 2005, but has mutated, in meaning, over time. The term Ajax now encompasses a number of alternate techniques for transferring data without need of a page refresh, i.e. Flash and iframes.

So you could say an Ajax request is quite an elusive fish, and you'd be right, if a little odd for using the word 'fish'. Aside from the multiple techniques that encompass Ajax, you have the fact that each technique is using the HTTP protocol. They are, in sense, mimicking a traditional browser request. So, there is really no way to tell the difference between a browser request and an Ajax request.

Am I saying that Request.IsAjaxRequest() doesn't work then? No, it'd be a pretty crap and decidedly pointless post if that was the case. I am in fact building a sense of excitement, and now the big reveal.

Request.IsAjaxRequest() is a test; a method for testing a request as it hits the server for one of two things:

  1. A header called X-Requested-With with the value XMLHttpRequest.
  2. The Request collection (encompassing QueryString and Form) contains a key value pair, where X-Requested-With is the key and XMLHttpRequest is the value.

Be advised that in both cases ASP.NET MVC is case sensitive.

What is particularly great about this solution is that, the convention is already in use in both the MSAJAX and jQuery libraries, as well as others I understand. If you prefer your JavaScript vanilla, then it is a simple step to apply either of the two prerequisites above.

Rich

Saturday, 27 February 2010

Ajax Forms with ASP.NET MVC and jQuery

This post uses jQuery, jquery.form.js, jquery.validate.js, ASP.NET MVC 2 and .NET 4.

I’ve been content loading my projects for a little while now using a graceful Ajax technique that combines jQuery with MVC PartialViews. Please see this post1 for more information.

This technique works fine with GET requests but I recently had a requirement for a form within some “content loaded” content. The whole point of content loading is that the HTML should be semantically correct and work without the need for JavaScript, so I obviously wanted to keep the form as clean as possible.

<div class="form-wrapper">
 <%= Html.ValidationSummary() %>
 <% using (Html.BeginForm("Edit", "Pages")) { %>
 <%= Html.EditorForModel() %>
 <input type="submit" name="submit" value="Submit" />
 <%= Html.Encode(TempData["Message"]) %>
 <% } %>
</div>

The example above is a very simple but incredibly scalable form thanks to EditorForModel, however notice that I’m not using any Ajax Extension Methods. I try to reduce dependence on the Microsoft JavaScript libraries whenever possible. This is not out of any particular dislike for those libraries, I just prefer jQuery and want to keep my file sizes down. The form above is placed in a PartialView, as per the fore mentioned Graceful Modals post, which is in term referenced by a parent View. We’ll call the View FormView and the PartialView _FormView.

We’ll also employ the Graceful Modals technique in the Controller actions, as seen below, by using AjaxView in place of View.

 // Edit
 public virtual ActionResult FormView(int id) {
  return AjaxView(_modelService.Load(id));
 }

 [HttpPost]
 public virtual ActionResult FormView(ModelOfChoice model) {
  if (!ModelState.IsValid)
   return AjaxView(model);

  // Save to Database
  _modelService.Save(model);
  TempData["Message"] = "Record Saved.";

  return AjaxRedirectToAction(MVC.Something.FormView(model.ID));
 }

A new method is used here called AjaxRedirectToAction, I’m still undecided on the best implementation, but a few signatures I’ve been playing around with can be seen below. You should also note that I try and create signatures to be compatible with T4MVC2 when possible.

 protected ActionResult AjaxRedirectToRoute(RouteValueDictionary routeValues, Func<ActionResult> ajaxCallback) {
  if (Request != null && Request.IsAjaxRequest())
   return ajaxCallback();

  return RedirectToRoute(routeValues);
 }

 protected ActionResult AjaxRedirectToRoute(RouteValueDictionary routeValues) {
  return AjaxRedirectToRoute(routeValues, () => { return Content("ok"); });
 }
 
 protected ActionResult AjaxRedirectToRoute(ActionResult result) {
  return AjaxRedirectToRoute(result.GetRouteValueDictionary(), () => { return AjaxView(); });
 }

The purpose of this method is to implement the Redirect-After-Post pattern for non JavaScript requests.

All that is left to do now is wire up the JavaScript. Firstly, I’m going to make slight change to jquery.form.js. The change deals with the over zealous caching by all versions of Internet Explorer, whereby IE doesn’t differentiate based on headers. By default Microsoft Ajax and jQuery use a header to signify that a request originates in JavaScript. When designing a graceful solution, you must accept that within the same session a user may access Actions with either a standard request or an Ajax request. If the user is exposed to a combination, we want to make sure the browser is displaying the correct output for the right request.

MVC makes allowances for the fact that not all environments allow custom headers to be sent with a request, by allowing the header value to be sent as a Query String parameter. IE does differentiate on Query Strings, so the change to jquery.form.js will add this parameter. The change is added at line 62.

 var ajaxified = url;
 if (ajaxified.indexOf("?") >= 0)
  ajaxified += "&";
 else ajaxified += "?";
 ajaxified += "X-Requested-With=XMLHttpRequest";

 url = ajaxified;

The last job is the wire up itself, which is an almost out-of-the-box implantation of jquery.validate.js and jquery.form.js. The code is below.

 $("form").validate({
  submitHandler: function(form) {
   $(form).ajaxSubmit({
    target: ".form-wrapper"
   });
  }
 });

At this point we should have a form that posts back to the server using Ajax or a standard page request, dependent on the existence of JavaScript. These forms should live quite happily within dynamically generated content and server rendered content.

A production implementation of this technique can be seen at http://21wappinglane.com.

  1. http://blog.dogma.co.uk/2010/01/graceful-modals-with-aspnet-mvc2-jquery.html
  2. http://aspnet.codeplex.com/wikipage?title=T4MVC

Sunday, 14 February 2010

Rolling with the Project Ball

A while ago I came across a post on Devirtuoso, on creating a 3D sphere using jQuery. There is fantastic demo on the post, but what really made it stand out was a lack of dependency on the canvas element, so it should be cross browser compatible. That is exceptional and when my colleagues found out about it, it was decided, this needs to power our new portfolio page.

“Okay”, I said. “That should be fine.” They do know how bad my maths is, don’t they?

The big idea. We are currently redeveloping the Ink Creations web site, the old site had been up for a few years and little had changed. We want the new site to be a reflection of the way we work/think with each page exploring a different aspect. Like a programmers playground, but more polished. One of these pages is our portfolio. We wanted to present our portfolio in an interesting new way while still remaining accessible. The 3D sphere gives us the interesting, but not so much the accessible. The sphere is comprised of plus signs that are generated in JavaScript, which are invisible to screen readers and search engines.

There are other issues with the sphere, in the context of our requirements:

  1. Each of the plus signs would need to be replaced with a unique portfolio image, but the rendering of the sphere allows for duplication of plus signs.
  2. The default behaviour of the sphere is to react to the position of the mouse, but to be constantly on the move. This makes tracking a particular plus sign very difficult. We would need our project images to be easily clicked.
  3. The plus signs are all the same solid colour, so there is no need to worry about the z-index of each element. With individual portfolio images, you don’t want the images at the back overlapping the ones at the front. No, no you don’t.

Lets deal with accessibility first. I still want to see a portfolio with JavaScript is switched off. The 3D sphere uses an unordered list which is good enough for me. So I start off by pre-rendering a list of each of our projects as an unordered list. Within the 3DEngine.js file I need to check for this and recreate the list if it doesn’t already exist.

//if there isn't a ul than it creates a list of +'s
if (container.children("ul").length === 0) {
	var $ul = $("<ul></ul>").appendTo(this.container);
	for (i = 0; i < this.pointsArray.length; i++) {
		var project = g_projects[idx];

		$ul.append("<li><img id=\"item" + i + "\" class=\"" + project.id + "\" src=\"/Image/Project/" + project.thumbnail.id + "?height=320&width=390\" /></li>");

		idx = nextIndex(idx, g_projects);
	}
}

I have created a global array of the projects called g_projects and have referenced it directly from 3DEngine.js. Now it is just a case of creating images instead of b elements. The pre-rendered ul list contains anchor tags as well, so the images are clickable. The fact that I haven’t done it in JavaScript is probably an oversight on my part. 

We are now accessible, with JavaScript switched off we get an unordered list of portfolio images. With JavaScript switch on the images form a spinning ball.

While we’re in 3DEngine.js, we’ll deal with the z-index.

currItem.style.height = (37.5 * currItem.scale) + "px";
currItem.style.width = (50 * currItem.scale) + "px";

$(currItem).css({ opacity: (currItem.scale - .5), zIndex: Math.ceil((currItem.scale - .5) * 100) });

Using the scale that has already been provided I’m adjusting the photo’s size, opacity and z-index. This should hopefully add to the illusion of depth.

Sphere.js is where I encountered some difficulty. As previously mentioned mathematics isn’t my strongest attribute. The Sphere objects constructor takes three parameters; radius, sides and numOfItems. These parameters make up the configuration of the resulting sphere and as such can’t be applied randomly, it would seem. For instance, increasing the numOfItems may well increase the number of portfolio images, but will not necessarily increase the complexity of the sphere. Additional images occupy the space of existing images leading to undesirable results.

I’m positive the relationship between the three parameters can be worked out mathematically, I just haven’t worked out that relationship yet. Until I do, my solution has been to control which images are created based on their coordinates. This will remove the chance of images occupying the same space, but does require a little fiddling (with radius and sides) as our portfolio increases. This isn’t a huge concern as I believe our current portfolio count is already testing the CPU usage or your average browser to it’s limits, but any help in determining the fore said relationship would be very much appreciated. The code for Sphere.js is below:

var Sphere = function (radius, sides, numOfItems) {
	var arr = new Array();
	var totalPerSide = Math.ceil(numOfItems / sides);
	var comparer = ["x", "y", "x"];

	for (var j = 1; j < (sides + 1); ++j) {
		for (var i = 0; i < totalPerSide; ++i) {
			if (this.pointsArray.length >= numOfItems)
				break;

			var angle = i * Math.PI * 2 / totalPerSide;
			var angleB = j * Math.PI * 2 / sides;

			var x = Math.sin(angle) * Math.sin(angleB) * radius;
			var y = Math.cos(angle) * Math.sin(angleB) * radius;
			var z = Math.cos(angleB) * radius;

			x = Math.round(x * 100) / 100;
			y = Math.round(y * 100) / 100;
			z = Math.round(z * 100) / 100;

			var points = { x: x, y: y, z: z };
			if (!arr.contains(points, comparer)) {
				arr.push(points);
				this.pointsArray.push(this.make3DPoint(x, y, z));
			}
		}
	}

	delete arr;
};

Sphere.prototype = new DisplayObject3D();

Array.prototype.unique = function () {
	var r = new Array();
	o: for (var i = 0, n = this.length; i < n; i++) {
		for (var x = 0, y = r.length; x < y; x++) {
			if (r[x] == this[i]) {
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
};

Array.prototype.contains = function (obj, properties) {
	for (var i = 0, n = this.length; i < n; i++)
		if (_equals(this[i], obj, properties))
			return true;

	return false;
};

var _equals = function (a, b, properties) {
	if (!properties)
		return a == b;

	for (var i = 0; i < properties.length; i++)
		if (a[properties[i]] != b[properties[i]])
			return false;

	return true;
};

I believe this leaves us with the issue of actually selecting a project and clicking on the image for more information.

var g_portfolio = (function () {
	$(document).ready(function () {
		if (g_speed && g_speed.isSlow())
			return;

		var camera = new Camera3D();
		camera.init(0, 0, 0, 300);

		var container = $("#item");

		container.css({
			margin: "0 auto",
			top: "46%",
			position: "absolute",
			left: "50%"
		});

		container.find("ul").css({
			position: "static"
		});

		container.find("img").css({
			position: "absolute",
			zIndex: 100
		});

		container.find("div").remove();

		var item = new Object3D(container);
		var sphere = new Sphere(175, 13, _projectCount);
		item.addChild(sphere);

		var scene = new Scene3D();
		scene.addToScene(item);

		var mouseX = 600;
		var mouseY = 0;
		var offsetX = $("#item").offset().left;
		var offsetY = $("#item").offset().top;
		var speed = 15000;
		var moving = null;

		$("#controls").click(function (evt) {
			evt.preventDefault();

			if (moving)
				stopTracking();
			else startTracking();
		});

		$("#item a").click(function (evt) { evt.preventDefault(); });

		$("#item img")
				.hover(function () {
					stopTracking();

					var $this = $(this);
					$this.data("state.3d", $.extend({}, { height: $this.height(), width: $this.width(), opacity: $this.css("opacity") }, $this.position()));
					$this.animate({ height: "+=18px", width: "+=18px", opacity: 1, top: "-=9px", left: "-=9px" });
				}, function () {
					var $this = $(this);
					var state = $this.data("state.3d");
					$this.stop(false, true).css(state);

					startTracking();
				})
				.click(function (evt) {
					location.href = "/portfolio/carousel/" + $(this).attr("class");
				});

		var animateIt = function () {
			if (!moving)
				return;

			if (mouseX != undefined) {
				axisRotation.y += (mouseX) / speed
			}

			if (mouseY != undefined) {
				axisRotation.x -= mouseY / speed;
			}

			scene.renderCamera(camera);
		};

		var mouseMove = function (evt) {
			mouseX = evt.clientX - offsetX - (container.width() / 2);
			mouseY = evt.clientY - offsetY - (container.height() / 2);
		}

		var startTracking = function () {
			$(document).mousemove(mouseMove);
			moving = setInterval(animateIt, 20);
		};

		var stopTracking = function () {
			$(document).unbind("mousemove", mouseMove);
			clearInterval(moving);
			moving = null;
		};

		startTracking();

		var $img = container.find("img");
		var imgCount = $img.length;
		var overflow = imgCount - sphere.pointsArray.length;

		if (overflow > 0) {
			var offset = (imgCount - overflow);
			var margin = 20;
			var withMargin = $img.width() + margin;
			var left = -((withMargin * overflow) / 2) + (margin * 2);

			for (var i = 0; i < overflow; ++i) {
				$img.eq(offset + i).css({
					left: left,
					top: 0
				});
				left += withMargin;
			}
		}
	});
})();

In the code above, I have refined the initialisation of the sphere to allow for the addition of a stop/start button. The sphere pauses when the mouse moves over an image, the said image then slightly increases in size to give emphasis. The last section of the above example deals with the remaining projects that didn’t fit within the sphere. It’s not ideal, but after running a few scenarios, I’ve found that I’m not able to guarantee a sphere that will encompass all projects, sometimes there is a remainder. These projects are lined up in the centre of the sphere.

And that is the current incarnation of our portfolio page. The full site is still under development and I’m sure the portfolio section still has some cosmetic changes to come. My prediction is some sort of featured projects sphere with a link to a full list. Until that happens, all the code is available uncompressed on the portfolio, when finalised and we’ve optimised the performance reasons, I’ll endeavour post the source to a follow up post. Our portfolio page can be found http://inkdigitalagency.com/portfolio.

Wednesday, 3 February 2010

jQuery plug-in for summing attributes

I love functions like foreach() and map() as a way for quickly arrogating through jQuery objects. I had a requirement to create a similar function today. I’m sure it has been done before but I couldn’t a direct equivalent within jQuery itself.

The function is called sum() and takes one parameter called “callback” and is directly related to it’s namesake in the map() function. The purpose of the function is to sum an attribute of each of the given elements. The “callback” parameter is a function that allows you to select the element’s attribute to be summed.

The summing component of the plug-in was taken from a code snippet on DZone.

The complete code along with an example is listed below:

/// <reference path="jquery-1.3.2-vsdoc.js" />

(function ($) {
 if (!Array.prototype.sum)
  Array.prototype.sum = function () {
   for (var i = 0, sum = 0; i < this.length; sum += this[i++]);
   return sum;
  };

 $.fn.sum = function (callback) {
  return this.map(callback).get().sum();
 };
})(jQuery);
var heightOfFirstElement = $(".element").height();
var combinedHeightOfAllElements = $(".element").sum(function () { return $(this).height(); });

Sunday, 31 January 2010

Graceful modals with ASP.NET MVC2 & jQuery

I don’t profess to understand all of what MVC2 has to offer in terms of Ajax interoperability, so I maybe off base with a technique I’ve been working on to create graceful modals with a minimal repetition of mark-up. So I welcome feedback inclusive of constructive criticism.

What do I mean by graceful modals? Well, I believe the web in general should make sense without JavaScript or CSS switched on. It won’t be brilliant or really exciting, but it should be work semantically with buttons and links that do stuff. No broken forms and no links that go nowhere.

Okay, but what about the modals? Well modals don’t make a lot of sense to a non JavaScript world and who wants pop-ups? The link (to the modal) has got to do something, so it might as well still link to the modal content. This is graceful, an anchor tag that opens up a modal when JavaScript is switched on but still links to content when JavaScript is switched off.

In the past I would have created a Web Service or a Page Method to populate the modal using XML or JSON. In the past I have even been known to pre-render the modal on the server.

Shudder.

While there is nothing wrong with Web Service/Page Method technique, it is very close to what I now use. But for me at least, the implementation involved repetition of mark-up, sometimes hard coded directly into JavaScript.

Yuck.

What do I do now? I use MVC2 exclusively for new projects. Before MVC came out I had found myself completely disillusioned with the Web Forms environment and was considering drastic steps towards Java or PHP. MVC saved me from such horrors, changing the way I think about the interaction between client and server.

To clarify, I found the PostBack model of Web Forms to restrictive and the Server controls full of semantically incorrect mark-up. Upset Web Form developers can just assume I’m to stupid to understand it. I was totally joking about PHP and Java, I wouldn’t have considered making the move if I didn’t have respect. But seriously after using VS2010 any other IDE would be like flints and rock. Ug-ug.

I’m pretty sure the technique I use works in MVC1 on .NET 3.5, but be warned any code samples will be illustrated using MVC2/.NET4.

The first thing I do when creating a modal window, is create a standard page (Index) that links to another very standard page (Index2). This is my foundation, it works absent of any enhancements that will be added later.

If you are familiar with MVC you will know that these pages are Views and the link is to an Action that returns the second of the two Views.

At the moment, the Action that returns the second of the two Views (Indesx2) returns a fully marked up HTML page including header and body tags, etc… This isn’t going to be any good for dynamically populating a modal, so we need to split out the mark-up that we want to display in the modal without any duplication.

Keep it DRY folks.

The best way to do this is with a Partial, so I’ll create one called _Index2. I picked up the underscore naming convention from another post (can’t remember which) and have found it very handy as you can run into problems naming your Partials the same as your Views. Especially when you start treating Views as Partials, but that is a another story.

I’ve put the main content portion of my Index2 View into my _Index2 Partial and now need to reference _Index2 (Partial) from Index2 (View), which is easily done with the following code:

<% Html.RenderPartial("_Index2"); %>

Which I have shortened ever so slightly to:

<% Html.RenderPartial(); %>

With the following helper that assumes the underscore naming convention:

public static void RenderPartial(this HtmlHelper helper) {
  helper.RenderPartial(String.Format("_{0}", helper.ViewContext.RouteData.Values["action"].ToString()));
}

My Index2 View now looks like:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
  <% Html.RenderPartial(); %>
</asp:Content>

And my Index2 Partial looks like:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<p>
  content</p>

I want to do one more thing to my mark-up. I will add a class to the anchor on my Index View to signify that I want the content to open up in a modal, which is shown below:

<%= Html.ActionLink("Index2", MVC.Home.Index2(), new { @class = "modal" }) %>

If you run all this now, you’ll notice no difference, clicking on the anchor in Index will still link to the Index2 View with content still intact. What I will do now, is create my modal. For the purposes of this post, I am just going to add a div called “modal” to my Master page. The fore mentioned div will be the container for our dynamic content.

Before we go on to the JavaScript, we need to make sure we can retrieve the content from Index2 without all the template HTML from the Master/View. To do this, I am going to enlist the help of a method I have created in the Controller called AjaxView. It works just like the View method but with an Ajax twist. The code is below:

protected ActionResult AjaxView(string viewName = null, object model = null) {
  if (RouteData != null && String.IsNullOrEmpty(viewName))
   viewName = RouteData.Values["action"].ToString();
  if (Request != null && Request.IsAjaxRequest())
   return PartialView(String.Format("_{0}", viewName), model);
 return View(viewName, null, model);
}

protected ActionResult AjaxView(object model) {
  return AjaxView(null, model);
}

The key to AjaxView is the extension method IsAjaxRequest. You can bing IsAjaxRequest for a full explanation but essentially the magic behind this method is in the client side libraries that support it. Libraries like jQuery and MsAjax add a header to Ajax requests to identify the request as being Ajax rather than a standard page request. IsAjaxRequest checks for this header and returns true if the header is found.

Our Index2 Action will now look like this:

public virtual ActionResult Index2() {
  return AjaxView();
}

With any luck, the standard page requests to /Home/Index2 will be directed to Index2.aspx and Ajax requests will be directed to _Index2.ascx. Let’s Ajaxify that request!

We’re going to do this with the following jQuery click event wrapped in a document ready event:

$("a.modal").click(function(evt) {
  var $this = $(this);
  $("#modal").html("");

  evt.preventDefault();

  var url = $this.attr("href");
  if (url && url != "")
   $("#modal").load(url, function(responseText, textStatus, xhr) {
    if (textStatus == "error") {
     $("#modal").html("<p>An error has occurred, please try again later.</p>");
     return;
    }

    if ($.isFunction(callback))
     callback(textStatus);
   });
});

The jQuery above attaches a click event handler to every anchor with a class of “modal”. The handler over overrides the standard click behaviour of the anchor and instead makes an Ajax request based on the anchor’s href attribute. The Ajax request is made using jQuery’s load function which is pointing at our modal div. The load function makes the request and populates the modal div with the response.

There we have it. Now, when we click on the anchor in Index (with JavaScript switched on) the page is not refreshed but instead the content from Index2 is dynamically loaded into the modal div. Clicking on the same link with JavaScript switched off still directs the browser to Index2 as before. This have been achieved with no duplication of mark-up using C# methods and JavaScript functions that can be reused with very little effort. Graceful.

Related Links

Saturday, 23 January 2010

Did everyone else know this?

We were messing around in a MVC 2 project the other day, when we came across a need to manipulate the class name of a DIV element in a Master Page from a View. I was going to start messing around with ViewData and whatnot but I really didn’t want to put too much effort into it. We were only likely to change the class name a couple of times so I wanted a quick and easy solution. Laziness is the mother of workarounds.

What we came up with was really quick and really easy, it also freaks Intellisense out. We put a Content Placeholder in the class value of the DIV. At the time it felt crazy, wondrous and groundbreaking, now it feels a little obvious. But I wanted to share anyway.

Here is a snippet from the Master Page:

<div class="<asp:ContentPlaceHolder ID="ClassName" runat="server" />">

And the corresponding View:

<asp:Content ContentPlaceHolderID="ClassName" runat="server">my-class</asp:Content>

Shazaaam! I can now tag up templated elements server side in mark up.

Twitter Updates