I recently came up with an approach to wiring up some jquery plugins that modify the behavior of standard input text boxes. The approach is not original by any means.I got the idea from the built in client side validation for MVC2, which was inspired by Steve Sanderson’s xVal framework.
The goal. I wanted a way to add both Watermark and Masked Input functionality to text boxes on my MVC views. I wanted to do this in an unobtrusive jQuery-ish way. I also did not want to reinvent the Editor templates or TextBox html helpers in the MVC framework. So I settled on this approach.
Lets look at some code.
The ViewModel marked up with some custom attributes to give a declarative way of defining the values used to bind to the plugins. I have added a Watermark and EditFormat attributes that are picked up by a modified ModelMetaDataProvider. This is what I use to specify the MaskedInput format (EditFormat) and the Watermark for the jQuery plugins.
A simple extension method to drop some JSON onto your page. This is nice and simple and could be moved into the object Editor Template if you wanted to just get this functionality by default.
The resulting page showing a Watermark plugin auto wired up.
The resulting page showing the Masked Input auto wired up for the Bar property. One the cursor is placed into the Bar text box the plugin hides the Watermark and applies the MaskedInput plugin.
What do you think of the approach? I did not supply a sample code as I have this working for a project at work and I did not want to let getting a sample together get in the way of getting this blog post up. If there is interest I can put together a sample, or better yet, maybe we can fit this into mvccontrib in some way..