Dogma/Geek Outlet for my techno babble.

18Aug/10Off

jQuery Remote Validation with ASP.NET MVC

Update 29/09/2010

I've included a sample project at the end of the post. The project can also be downloaded here: RemoteValidation.zip.


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.

You can download a sample project at the following location: RemoteValidation.zip. If you're just interested in the amended MicrosoftMvcJQueryValidation.js file, it can be downloaded here: MicrosoftMvcJQueryValidation_remote.js

13Jul/10Off

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

27Feb/10Off

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
14Feb/10Off

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.

Filed under: Javascript 2 Comments
3Feb/10Off

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(); });
31Jan/10Off

Graceful modals with ASP.NET MVC2 & jQuery

Update 28/09/2010

I've included a sample project at the end of the post. The project can also be downloaded here: GracefulModals.zip.


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(), null, 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.

You can download a sample project at the following location: GracefulModals.zip.

Related Links

21Feb/09Off

JavaScript/CSS bookmark tip for Visual Studio

pixlr

Visual Studio is great, Visual Studio 2008 Standard Edition is my favourite iteration so far and the best IDE I’ve had the pleasure of using. I sometimes think that the only reason I don’t stray into Java and PHP is because it’d mean giving up Visual Studio. I cannot state this strongly enough, Visual Studio is great.

There is always room for improvement however, and in this post I am suggesting a workaround to make working with JavaScript and CSS a bit easier.

When working with C#, VB, (X)HTML, XML, etc… in VS2008 you have a number of ways to make large files more manageable. XML tags are collapsible, as are C# and VB methods and classes. You can also create collapsible regions to group collapsible objects together. There are drop down lists and class views for jumping to specific objects and sections. There are a lot of sign posts in VS to prevent you from getting lost.

Unfortunately, none of this exists for JavaScript and only a limited amount for CSS. Especially unfortunate as both of these file types can become quickly unwieldy. It is tempting to split JavaScript files into smaller more manageable files, using jQuery plugins as an example. But when your trying to keep HTTP Requests to minimum, recombining JavaScript files can be laborious. The situation with CSS files is less dire because of the class view, but a big web site usually means big CSS files and the class view doesn’t always cut it for me.

My tip is quite an obvious one, I can’t believe it has taken me so long to work it out. The tip is bookmarks, I know clue in the title. By chopping up your code into logical sections and assigning each of those sections a bookmark, large files become a great deal easier to navigate. I told you it was obvious, I’ve been using bookmarks since Word ‘97.

Adjusting the environment to my requirements was straight forward. I’ve given up trying customise keyboard shortcuts, there just too many. I hate chords! So, my first step was to create a new toolbar (called Bookmarks). In the newly created toolbar I placed three buttons from the Edit menu, “Enable Bookmark”, “Prev Bookmark in Doc” and “Next Bookmark in Doc”. The first toggles the bookmark on or off at any given location, the second two allow me to navigate my JavaScript and CSS files a lot more efficiently.

That’s it, sorry if it’s a bit anticlimactic, but it has really sped things up for me.

Filed under: CSS, Javascript, Tips No Comments
20Feb/09Off

Bookmarklets

Bookmarklets

I’ve been using bookmarklets for a while now. I find them to be great time saving devices, so I’m always surprised when I’m confronted with people unaware of the phenomena. In an attempt to correct this wrong, I present this post. The purpose of the post is not spend a great deal of time explaining what they are, Wikipedia does it more comprehensively here. What I’ll actually try to do is tell you how I use bookmarklets. Then, having never heard of bookmarklets before, you’ll be able to decide if bookmarklets are for you.

So very briefly, bookmarklets are browser shortcuts that contain JavaScript (like JavaScript in an Anchor tag). When you hit the bookmark, the said JavaScript performs a task, generally, in relation to the page you are on. As I say, more info here. Be careful though, don’t just drag any old nonsense into the bookmarks bar, make sure it comes from reputable source.

I mainly use bookmarklets for social networking and communication, whether it’s bookmarking to Delicious or composing an email with Google Mail. Here is a list of some of the socially orientated bookmarlets I use, a brief description, and when possible, the source url.

Bookmark – The “Post to Delicious” bookmarklet from Delicious. Clicking “Bookmark” brings up a Delicious dialog that allows you to enter tags and a description for the current page.

Compose – Found here, this bookmarklet brings up a Google Mail Compose window, as if you’d opened it directly from your Google Mail account. I had to alter the url embedded in the JavaScript slightly to work with my Google Apps account.

Share – My friends on facebook get an influx of links throughout the day because of this bad boy. The bookmarklet can be found in the Posted Items section of facebook and works in a similar fashion to the Delicious bookmarklet. You can also send links directly to your friends, rather than sharing with everyone.

Subscribe - Not used so much now as I tend to use Twitter as my primary source of information, but still handy. This bookmarklet, supplied by Google Reader, detects RSS feeds on the current page and subscribes them to my Google Reader account.

Twitlet – As my latest find, this bookmarklet prompted this very post. Twitlet allows me to tweet from a JavaScript dialog, I can also use shortcuts to provide context to the current page. I’d like to see a nicely styled popup in the future, but still very useful. The bookmarklet can be found here.

In addition to social networks, I also use booklets in my development. Admittedly a lot of them tend to fall by the wayside as similar functionality appears in Firebug or alike. One bookmarklet that has stood the test of time is Visual Event. Visual Event provides a visual reference for all JavaScript events registered on the current page. Current JavaScript libraries (at time of writing) include, jQuery, Prototype, MooTools and YUI. A wholly more accurate description can be found here.

Well that’s it, great personalised functionality with cross browser support. I’ve even got my Delicious and facebook bookmarklets working on my iPhone. Rock on.

Filed under: Javascript, Tips No Comments
16Nov/08Off

The Intellisense Tree

Weird TreeWhen I embark on a new project I, like other people, have my own little routine/ritual that I perform. After I've created the Visual Studio project file, I go ahead and create my preferred folder structure along with with some blank files that I expect to utilise at some point later on. A lot of this could be contained within custom Visual Studio templates, which I do use, but my ritual is organic and as such is constantly evolving. So templates tend to waste more time than they save.

Part of my ritual (I prefer ritual to routine) is to create a folder structure to house my JavaScript. The root folder is called 'script', within the root folder I create two further folders 'intellisense' and 'min'. Within the root folder I also place my JavaScript working files, the files that generally represent the mess that is my head.

Inside the 'min' folder go the minified versions of the working files, these file are usually created towards the end of the project and constitute the production files. I use Packer.NET which is based on Dean Edward's JavaScript packing script, packer.

The files within the 'intellisense' folder contain code representations of the working code. The code is a representation of the working code in as much as the functions are usually shells with altered parameters and returned objects to provide more context. The code within the 'intellisense' files also contain XML to further enhance the, um, intellisense. This was until I found out about a feature of VS 2008 that attempts to automatically detect the JavaScript working file's related intellisense. Automatic detection sounds like a great feature but I'm not sure how I feel about it.

In order to explain my apprehension I must first explain that while I have longed dreamed of automatic detection of my intellisense files, those odd, slightly dull dreams allowed more control over how those files were detected. I like having my intellisense files in different folders, it keeps everything clean and organised. In certain situations (e.g. jQuery plugin development) I like to keep version details in the file name. I have another reason for not being quite so impressed, but I'll get to that in a minute.

JavaScript Tree

For now I just want to explain how this detection works. If you create a JavaScript file called script.js, Visual Studio will look for one of two files in the following order: script-vsdoc.js or script.debug.js. If script-vsdoc.js is found, script.debug.js is ignored. If Visual Studio finds one of these two files, VS will refer to the file for intellisense rather than script.js.

This leads me to my second disappointment. When I first heard that Visual Studio was looking for two files, my hope was that one of the files would represent my working file, leaving script.js to be my production minified file. In the scenario in my head, script-vsdoc.js is intellisense, script.debug.js is my working file and script.js is the seldom edited production file. This rather fantastic set-up (ignoring that lack of control over naming and location conventions) would only be made more wondrous by the ability to add something like Dean Edward's packer script into the build process where script.js is automatically generated from script.debug.js.

Alas, I was mistaken and destined to be disappointed by a feature that is actually a fairly decent time saver. Will I use it in my ritualin the future? I am already using the vsdoc naming convention for the purposes of automatic detection in one of my existing projects, though I suspect I will not utilise this feature in the next project I work on.

What could ultimately be done to make this feature more usable for me in the future is:

  1. Give me control of where VS should look for related files. I don't like clutter. At the very least collapse the vsdoc file under the working file.
  2. I'd like automatic detection to ignore the middle of the filename for the purposes of version control.
  3. This isn't a deal breaker, but I'd like the concept of a production file worked into the mix. I sure there must be away to make a tool like Packer.NET part of the build routine.

I'm not entirely sure what the point of this post was. I have wanted to express a need for JavaScript and CSS compression as part of the VS build routine for a little while. I also wanted to describe small feature of Visual Studio intellisense that may have escaped your radar if you do not use jQuery. Automatic detection is specific only to JavaScript, but it has been recently popularised by ASP.NET's alignment with jQuery.

Filed under: Javascript No Comments
30Oct/08Off

New Time & Date UI Demo Page

I've created a demo page for the Time & Date UI jQuery plug-in. It was a good experience that has highlighted a couple of areas for improvement as well as a bug with the US input format. I guess this is why we call them BETA's.

The link to the test page is http://dogma.co.uk/plugins/timedateui/.

Switch to our mobile site