Unobtrusive attachment of functions to events in jQuery


Lets say I have text input field that is part of search form, and when user clicks on find, it gets results in another part of screen. What I want is, when user changes value in some of the inputs of search form, that search results be invalidated/removed as they are not actual anymore.

As search form can have many fields, I decided to make one function for resetting search, and to make unobtrusive attachment for “change” event. I did that by adding “change” attribute to input field:

<input name="Search.SomeValue" class="valid" id="Search_SomeValue" change="resetSearch" type="text" />

This attribute is consumed by this function:

        var functionName = $(this).attr("change");
        var change = window[functionName];

What this code does is:

– For each element with change=”something”, read something (in this case “resetSearch”) into functionName variable

– Read function from window object. Window object contains all globally defined functions

– Set this function to execute on every change of input field


Deserialize form from JSON data using jQuery

Recently, I got task to make feature which will make possible for user to update form data based on some unique “search” field (like VIN or SSN). I wanted to make this short and simple, and above all reusable. So, I made some investigation this weekend and came up with simple solution to use same model object that is used as type of view in mvc. It is simple javascript function:


var formPrefix = 'myFormPrefix';
$('sometextbox').change(function () {
 var myValue = $(this).val()
 $.ajax({ type: 'POST',
  url: 'ajaxcontroller/getcarbysomething',
  data: { something: myValue },
  success: function (data) {
  if (data){
   $("input[name*='" + formPrefix +"'],select[name*='" + formPrefix + "']").each(function () {
    var itemName = $(this).attr("name");
    var prop = itemName.substring(itemName.indexOf(formPrefix) + formPrefix.length);
    var itemValue = data.person[prop];
    if (itemValue && itemValue.substring &&
      itemValue.substring(0, 1) == "/" &&
      itemValue.substring(itemValue.length - 1) == "/") {
         itemValue = "new" + itemValue.substring(1, itemValue.length - 1);
         itemValue = eval(itemValue);
         $(this).datepicker("setDate", eval(itemValue));
    else if (itemValue) {

So, to use this you need to make controller action that returns JsonResult and Json(model) instead of View(model). If form is partial view (preffered) or has explicit prefix, formPrefix is place to set it. Each form input element’s name is used to index json object returned from controller and value (if any) is set back into input element.

Autocompleting cascading dropdowns


Starting point for this post is source code for last one, available on bitbucket.

I want to replace dropdown list with jQuery autocomplete, like in this example. There are two reasons for this:

  • When there is very large number of records to choose from, then standard dropdown list is not very user friendly
  • When user is entering name of item, besides autocompleting from known items, we can implement addition of new item if item user needs to enter is not present in codebook. This will be done in next post.

For start, I will copy example from jQuery demo, and add textbox in which I will implement this functionality.


I have added this code to Index.chtml, which is label for manufacturer, hidden field with id for chosen value from dropdown, and textbox for autocomplete. I have added three attributes for this textbox:
– autocomplete-for is target (hidden field) into which I want to place chosen value
– from-url is address where I will get items for autocomplete
– parent is field for cascading functionality (this will be optional)

Client side code for autocomplete is based on jsonp example from jQuery ui demo:


I have added this init function to document ready event. What is happening here is simple: for each input element that has “autocomplete-for” attribute, jQuery autocomplete is added, with custom function as data provider. This function is using ajax to request data for dropdown from from-url specified in view. Parameters are MaxItems (amount of items to show in autocomplete), ParentFilterId (selected value of parent field – for cascading support) and NameStartsWith, which is text entered into dropdown which is autocompleted.

Success function maps “items” collection in response to label, value and id. label and value are automatically used by autocomplete plugin to show label for item in dropdown and to set textbox value when item is selected, and I added id to set hidden field in select event.

To make this work, there is one thing left: controller action which will return items. As you can see in first screenshot, I decided to use Manufacturer controller and action named Autocomplete.

To make parameter passing easier, I have created model for data passed in request:


I will receive this object as parameter in my action.

This is how implementation of autocomplete action looks:


This is fairly simple – query is filtered by name for NameStartsWith parameter, and I used ToLower method of string, to compare case insensitive, as StartsWith with string comparison options parameter is not supported in linq to entities.

If request contains parent filter id or max items number, then these are taken into account, and response is formed as collection of items with Text, Value and Id properties, which are used in success function of ajax request.

Time to see how it works:


As this is working nicely, time for little makeup, as I want this more reusable, and not having to remember html attributes that need to be used. So, that smells like html helper:


Actually, it is two helpers – one for cascading case, and one for “normal”. It is the same code as in cshtml view, but creating hidden and text field in one method, and when I add comments here (removed to make screenshot smaller), I will have nice intellisense to use this function whenever I need, only having to copy and adjust controller action, which also can be made pretty generic.



This is how autocomplete is used now. I’m ready to call this a day, and source code from this post is in this changeset on bitbucket.

ASP.NET MVC3 app (part 3) – ajax cascading dropdown–unobtrusive version


In part 2, I made cascading dropdowns by calling selectFromAjax javascript function from my view:


This function has 3 arguments: address of service which provides data based on second argument – formData (in this case only id of selected item in current dropdown), and target – select list into which items from service are injected, replacing its current contents. These three parameters are almost enough to know that there is dependency between two dropdowns. Why almost? Because there is one implicit parameter – this function is part of “change” event of another dropdown – source of this event. So, source dropdown is fourth parameter. That four things are everything that client needs to know to be able to implement intended behavior of UI.

I will make this functionality unobtrusive by placing necessary information into target dropdown. Why? Because it seems most straightforward and “unobtrusive” to me, that dropdown list says “My contents depend on item selected in dropdown list X, and you need to call service Y to find out what should I show”. It is not ok to have information about MY behavior in some other dropdown X Smile. Besides, with this approach, I’m eliminating one parameter, as I have only two now: dropdown X and service Y. Third was value of dropdown X, and fourth is target dropdown itself, into which I’m adding these attributes. Value of dropdown X I can read if I know which is dropdown X, so this parameter for function anyway must be determined at the moment of changing value in X.

So, if I make my select look like


then my dropdown contains all information needed to remove script from view, and place it in global js file, or make jQuery plugin. To make this information automatically embedded into my dropdown, I need to make html helper for this. If wee look at first overload of DropDownListFor in System.Web.Mvc.Html.SelectExtensions, we can easily see how new method should look:


My html helper will have another two arguments – depends on and load from:


It is using DropDownListFor helper from Microsoft, and I won’t render my own html code (and so make more space for bugs Smile).

So, view from part 2 should now look like this:


and generated html is:

<select cascading-dependson="ProductType" cascading-loadfrom="/Home/Manufacturers" id="Manufacturer" name="Manufacturer"></select>

Now, all that is left, is to automatically attach event handler onto “master” dropdown. It is easy using jQuery:

imageThis is adding initializeCascader to list of functions that are run on document load. This function goes through each select that has cascading attributes and attaches onchange event to element with id in cascading-depenson attribute, with self as a target for selectFromAjax function (from part 2), and value of cascading-loadfrom attribute as a url.

This is very simple concept, but can be used for chaining random number of dropdowns, and can easily be expanded to make dropdown values dependent not only on “master” dropdown, but to depend on whole form. Further improvement of this could be custom data annotation attribute, which could be used for decorating property of model, so html helper does not have to be explicitly called.

Source code for this post can be downloaded here.

UPDATE: I have uploaded source code to bitbucket.

Back to part 2

ASP.NET MVC3 app (part 2) – ajax cascading dropdown


To make cascading dropdowns in application from part 1, I created ProductFilter:


I will use this class as model for my home controller Index method:


Here you can also see Manufacturers JsonResult method, which is used for asynchronous refresh of second dropdown:


Manufacturer dropdown is loaded with manufacturers which produce models of chosen product type. This is made possible with simple jquery function:


This function accepts url of method which provides json list of items for dropdown, passes formData parameter with id, and places results into target for which selector “target” is provided.

This is how my view from which this method is called looks:


Two dropdowns are created using standard MVC helpers, and onchange event function is attached using jquery. More dropdowns can be chained in the same way, there is only necessary to add change function in the same manner. However, this is no good, as event attachment is manual, and script must be written, and included into view as selectors are generated here. My goal is to make these event attachments unobtrusive, and I will write about that in part 3.

For now, you can download project source code here.

Back to part 1