HtmlHelper methods and dijit widgets

This is certainly not earth-shattering but it’s pretty cool. Asp.Net MVC HtmlHelper methods return a string of html and are used to render html elements. They are cool because you can use them to change the way the control is rendered at runtime based on what you’ve got in ViewData or your model. What’s even cooler is that you can pass html attributes (including custom ones like dojoType) to the HtmlAttributes parameter. This allows you to use HtmlHelper methods to render dijit widgets like so:

<%=Html.TextBox("search_StreetAddress",
    Model.Criteria.StreetAddress,
    new { dojoType = "dijit.form.TextBox", trim = "true" })%>

<%= Html.DropDownList("CityId", Model.CitySelectList,
    new { dojoType = "dijit.form.FilteringSelect" })%>

<%= Html.TextBox("Year", Model.Year,
    new { dojoType = "dijit.form.NumberTextBox",
          constraints = "{min:1900, max:2500, pattern:'0000'}",
          required = "true",
          rangeMessage = "A 4 digit year is required",
          invalidMessage = "A 4 digit year is required" })%>

Using dijit.form.DateTextBox with Asp.Net

Since there’s no date literal in javascript, there’s no standard way of serializing/ deserializing dates. MS Ajax uses \/Date(<ticks>)\/ where ticks is the number of milliseconds since midnight 01/01/1970. It’s a reasonable approach – unambiguous and easy to transform in both directions. For a while I was transforming this date object into a date before sticking it into a dojo DateTextBox, and transforming it back before sending it up to the server. But then I got smart and extended dijit.form.DateTextBox to handle this itself. Here’s the code:

dojo.provide('mjuniper.widgets.DateTextBox');
dojo.require('dijit.form.DateTextBox');

/*A dojo datetextbox that handles sending dates
to and recieving dates from asp.net*/
dojo.declare('mjuniper.widgets.DateTextBox',
    dijit.form.DateTextBox,
{
  // prevent parser from trying to convert to Date object
  value: "", 

  postMixInProperties: function()
  {
    this.inherited(arguments);

    //if it's null, return
    if (!this.value)
    {
      return;
    }

    if (this.value.indexOf('/Date(') > -1)
    {
      //extract the ticks from the json object
      var ticks =
          this.value.substring(this.value.indexOf('(') + 1);
      var endChar = (ticks.indexOf('-') === -1) ? ')' : '-';
      ticks = ticks.substring(0, ticks.indexOf(endChar));
      //instantiate a date
      this.value = new Date(parseInt(ticks));
      //if it's invalid, set value to null
      if (this.value == 'Invalid Date') { this.value = null; }
    }
  },

  /*override the serialize method to write
  back to the server in proper format*/
  serialize: function(dateObject, options)
  {
    return '\/Date(' + dateObject.getTime() + ')\/';
  },

  /*override setValue so we can set it with the
  json date object we get from .net*/
  setValue: function(dateString)
  {
    if (dateString.indexOf('/Date(') > -1)
    {
	//extract the ticks from the json object
	var ticks =
	  dateString.substring(dateString.indexOf('(') + 1);
	var endChar = (ticks.indexOf('-') === -1) ? ')' : '-';
	ticks = ticks.substring(0, ticks.indexOf(endChar));

	arguments[0] = new Date(parseInt(ticks))
	this.inherited(arguments);
    }
  }
});

There are obviously a number of ways I could have handled extracting the ticks from the json string (including a regex, but then I would have had two problems). This one is not very elegant but it’s relatively easy to understand and I was able to get it working quickly.

My dojo top ten (part 3: hitch)

I think I will call my series of posts dealing with dojo.query and NodeList part two of my dojo top ten and move on to part three.

I’ve come to rely heavily on dojo.hitch but at first I didn’t understand it at all. And I haven’t found many good explanations of it online (except this one) so I’m going to try my hand at a simple concise explanation of hitch.

Here we go: hitch returns a function in which ‘this’ will be whatever is specified as the first argument to hitch.

I’m now using it elsewhere but hitch is particularly useful with callback functions. So here’s an example:

dojo.xhrGet({
  url: 'http://mywebservice.com/helloworld',
  load: helloworldCallback

So we’re calling a webservice and specifying the callback function as helloworldCallback. This is all well and good but if you try to use ‘this’ in helloworldCallback, say to call other functions in the same module, it may not be what you expect it to be. Enter hitch:

dojo.xhrGet({
  url: 'http://mywebservice.com/helloworld',
  load: dojo.hitch(this, 'helloworldCallback')

By using hitch in the above example, we guarantee that when we hit the callback function, ‘this’ will refer to what we expect it to (in this case the module that contains both helloworldCallback and the function that does our webservice call).

dojo.query – putting it all together

So I guess this will be the finale to my series of posts on dojo.query. I’m using dojo.query to validate data entered into dojo dialogs. In this post, I discussed getting dialog content from an Asp.Net MVC controller method. In the onDownloadEnd function, I do any setup of the dialog that is necessary including something like this:

var onValueChanged =
        dojo.hitch(this, this.dialogValueChanged, dialogId);
//gotta be keyup -
        //validation is out of sync if you use keydown or keypress
dojo.query('input[type="text"], textarea', dialogId)
        .connect('onkeyup', onValueChanged);
dojo.query('select', dialogId)
        .connect('onchange', onValueChanged);
dojo.query('.dijit', dialogId).widgets()
        .connect('onChange', onValueChanged);

This query’s for input elements in the dialog and connects each element’s appropriate method to the function where I do the validation (dialogValueChanged). Note the use of the widgets method discussed in this post.

Here’s the validation function:

dialogValueChanged: function(dialogId)
{
  //check if everything is valid
  var valid = dojo.query('[widgetid], [widgetId]', dialogId)
    .widgets().every(function(widget)
    {
      if (widget.isValid)
      {
        return widget.isValid();
      }
      //if it is not a widget
      //or does not have an isValid method, return true
      return true;
    });                                

    //enable/ disable the save button based on whether it's valid
    var action = (valid) ? 'removeAttr' : 'attr';
    dojo.query('.dialogSaveBtn', dialogId)
	  [action]('disabled', 'disabled');
}

Here we’re querying for widgets and using our previously discussed widgets method to get the actual widgets (not just the dom nodes). Then we use the every method of NodeList to call the isValid method on each widget. The every method will return false if any of the widgets’ isValid methods returned false. Then we use the value returned from every to set our ‘action’ variable and use query again to enable or disable our save button(s) by adding or removing the disabled attribute. Note the use of the removeAttr method we added to NodeList in this post. Note also that this all depends on all the input elements on the dialog being dijit widgets. This mechanism can be easily extended to handle non-dijit elements too.

More dojo array processing goodness

I use dojo.forEach everywhere. One thing that I occasionally need that dojo.forEach can’t do (as far as I know) is break out of the loop early. Thanks to Eugene Lazutkin I realized that I can just use dojo.some or dojo.every to break early. By the way, you should read that whole article – there’s lots of good stuff there.

Let’s say that you’ve got an array of objects and you need to know the index of one of the objects in the array based on a property value. Consider these two functions that will both accomplish this:

GetArrayItemIndex: function(ary, item, fieldName)
{
    var i = -1, result;
    dojo.forEach(ary, function(aryItem)
    {
        i++;
        if (aryItem[fieldName] === item[fieldName]) { result = i; }
    });

    return result;
}

GetArrayItemIndex2: function(ary, item, fieldName)
{
    //using some instead of forEach to break early
    var i = -1;
    dojo.some(ary, function(aryItem)
    {
        i++;
        return (aryItem[fieldName] === item[fieldName]);
  });

      return i;
}

GetArrayItemIndex uses dojo.forEach so it will go through every item in the array even if the item we’re looking for is at index 0. GetArrayItemIndex2 uses dojo.some to short-circuit the loop when we locate the item we’re looking for. I’ve been wondering about this for a while – I’m glad I finally googled it today and discovered Eugene’s post.

Fun with dojo.io.iframe.send

One of my projects has had functionality to export a map image for some time. To get the map image, I just call (javascript) window.open and point the url to my http handler that will return the map image (with additional querystring parameters that specify the map parameters). This was working fine but now the customer wants to include lots of other markup on the map, including stuff they’ve drawn on the map with the nifty drawing tools I’ve provided them. This presented a bit of a problem because if I continued to just use window.open, the querystring was gonna get really long. So I realized I’d have to post the map parameters to my handler. But as far as I know, there’s no way to post data when you call window.open. So what to do?

The first thing I thought of was that I could post the parameters using dojo.xhrPost and then prepare the image and return the url to it. Then I’d call window.open with the url returned from the first request. I didn’t really like that. For one thing, it would be two requests, but for another, I’d have to keep that map image around in some manner.

So I decided to use dojo.io.iframe.send. This ended up working very well but I did run into a few issues that I thought I’d share.

One thing that I didn’t realize at first is that dojo expects the response to be an html document. And if you want to return anything other than an html document (json or text for example), you must wrap it in an html textarea. Dojo will look inside the first textarea in the response document and return to your handle, load, or error functions whatever it finds there in the format you specified in handleAs (defaulting to text if you did not specify one).

Another thing I ran into was that my dojo.io.iframe.send call would only work once per page load. I’m not exactly sure why that is. I found a suggestion that you set a timeout on the __IoArgs object passed to iframe.send. That worked in the sense that I could call it again after the timeout expired but I have no idea how long this operation is going to take so it’s hard to know what to set the timeout to. My solution was to keep a reference to the dojo.Deferred object returned by iframe.send and call cancel on it before trying to send another request like so:

if (this.getMapImageDeferred)
{
  this.getMapImageDeferred.cancel();
}


This seems to work fine but I do have to check in my errBack function whether the request was canceled:

_mapImageCallbackError: function(response, ioArgs)
{
  if (response.message === 'Deferred Cancelled')
  {
    return response;
  }
    // handle the error...
},


The last thing I ran into really had me stumped. I was setting method = “post” in the __IoArgs object passed to iframe.send but it was always using get. I read a few things here and there that kind of seemed to suggest that if I passed a form with its method set to ‘post’ into __IoArgs that might do the trick. And it did! So here’s what I’m doing now:

//create a form with method=post
var form = document.createElement('form');
dojo.attr(form, 'method', 'post');
document.body.appendChild(form);

//create my postdata
var content = {
  /*set a bunch of parameters here that
  will be posted to the http handler*/
};

//make the request
this.getMapImageDeferred = dojo.io.iframe.send({
  url: path + 'map.mapimage.aspx',
  form: form,
  content: content,
  error: dojo.hitch(this, this._mapImageCallbackError)
});

//get rid of the form created above
document.body.removeChild(form);


I’d be interested to know if anyone else has run into these issues and how you resolved them.

Extending dojo query part 2

One of the cool things about the dojo NodeList is that most (all?) of the methods of NodeList return the list so you can chain NodeList operations ala jQuery. I realized that I had overlooked this with my removeAttr method when I wrote this:

dojo.query('#okConfirmBtn', dialogId).removeAttr('disabled').
  connect('onclick', clickFunc);



This would fail because removeAttr doesn’t return anything. It’s a simple change though, here’s the updated code:

//extend nodelist to have a removeAttr function
dojo.extend(dojo.NodeList, {
  removeAttr: function(attribute){
    return this.forEach(function(item) {
      dojo.removeAttr(item, attribute);
    });
  }
});


I also created another extension to the NodeList, a widgets method. This filters the NodeList to only nodes that are widgets and returns a NodeList of the widgets (not the dom nodes, the actual widgets).

/*extend nodelist to have a widgets function that
filters the list and returns a nodelist of dijit widgets*/
dojo.extend(dojo.NodeList, {
  widgets: function(){
    return this.filter(function(item)
    {
      var widget = dijit.byNode(item);
      if (widget) { return true; }
    }).map(function(widget) { return dijit.byNode(widget); });
  }
});

Extending dojo.query

I’ve been making more and more use of dojo.query. In case you’re not familiar with it, it basically allows you to query the dom using css syntax. It returns a NodeList which is an array of dom nodes with some extra dojo goodness built in. Like many (all?) of the dojo array processing functions, some of which I discussed here. NodeList also has some handy methods like addClass, removeClass, toggleClass, style, addContent, and a few others. NodeList.attr will set an attribute on every node in the nodelist. Very handy, but there’s no NodeList.removeAttr, I’m not sure why. I needed this functionality in a bunch of places. At first I was just using NodeList.forEach, but then I realized it would be better to just extend NodeList like so:

dojo.extend(dojo.NodeList, {
  removeAttr: function(attribute){
    this.forEach(function(x) { dojo.removeAttr(x, attribute); });
  }
});



That little bit of code adds the removeAttr function to NodeList! Now I can just do this:

dojo.query('foo').removeAttr('bar');



I’m doing something else with this that I think is interesting. I’m using alternative syntax (that probably has a name but I don’t know what it is) to reduce the amount of code I’m writing. For instance, instead of writing this:

if (valid)
{
  dojo.query('.detailSaveButton').removeAttr('disabled');
}
else
{
  dojo.query('.detailSaveButton').attr('disabled', 'disabled');
}



I’m doing this:

var action = (valid) ? 'removeAttr' : 'attr';
dojo.query('.detailSaveButton')[action]('disabled', 'disabled');



Note that the second argument being passed in will be ignored if action == ‘removeAttr’.

Asp.Net MVC + dojo dialog

I’ve bee working a ton with dojo and we recently started doing several projects using Asp.Net MVC.

I’ve made fairly extensive use of dojo dialogs (dijit.Dialog) and thus far I’ve usually just declared the dialog in markup because it was easy and most of the samples do it that way. But I was never totally satisfied with that. But last week I realized something cool: you can create a dojo dialog in javascript and set its href property to an Asp.Net mvc controller method that returns a view user control! This is cool for lots of reasons: you can separate the dialog markup from the rest of it, you only create the dialog if you actually need it, and best of all, the view user control can be used to conditionally render the dialog (enable/ disable controls, show different controls, etc) based on what you’ve got in viewdata, your model, or session state.

So I realized this should work in theory but I expected to have to fiddle with it to get it to actually work. Nope, it just works.

Some sample code:

Controller method:

public ActionResult GetDialog()
{
    var model = new RoleDialogModel();

    model.foo = this.foo;

    return View("RoleDialog", model);
}

Pretty straightforward, just create the model, set some properties and return the view, passing it the model. I won’t show you the view – just create a view user control and stick some markup in it.

Javascript:

showDialog: function(title, action, evt)
{
    //first check if it's there so we don't create a duplicate
    var dialog = dijit.byId('fooDialog');
    if (dialog) { dialog.destroyRecursive(); }

    dialog = new dijit.Dialog({
        refreshOnShow: true,
        id: 'fooDialog',
        title: title,
        onDownloadEnd: dojo.hitch(this, this.initializeDialog, action, evt)
    });

    dialog.setHref(this.dialogUrl);

    dialog.show();
}

There are a couple of things to notice here. First, I check if I’ve already created the dialog, dojo will puke if you try to create two objects with the same id. If it’s there I destroy it. I was previously just resetting its properties but the title wouldn’t change. I know I saw a post somewhere about how to do that but for now, I’m just destroying it and re-creating it. I set onDownloadEnd to an initialization function which hooks up ui events, etc. You should do any dijit widget stuff here, to be sure the widgets are there when you go looking for them. The setHref function sets the href of the dialog to the controller method above. I realized after I got this working that setHref is deprecated and you should use the href property instead but it was working so I didn’t want to mess with it.

I think this is a great way to handle dojo dialogs in an Asp.Net MVC app. I plan to continue using this approach and refine it going forward.

Accessing ASP.Net Web Services With Dojo (part 2)

It looks like Dave ran into an issue similar to the one I discussed in my previous post on this subject. Only he solved the problem. I should have been using dojo.rawXhrPost.