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.

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.

Re-throwing exceptions in .Net

I knew that I read somewhere that there was a very important difference between throw; and throw ex; when you catch an exception and want to re throw it. But I couldn’t remember what the difference was. Thanks to this post I now know. If you use throw ex, the stack trace info will be overriden. So it is almost always preferable to use just throw.