Many times you will see the need to implement a Facebook style autocomplete textbox. Auto-complete functionality is great because it allows the end user to easily make selection(s) for a given data field.

We had a scenario where we wanted the user to enter multiple states that he is interested in. Of course, FCBKComplete is the best open source plugin for Facebook style auto-completion.

This post should give you a quick idea on how to configure the auto-complete item.

The control can simply be created using the following lines of code:

<select id="stateSelection" name="stateSelection[]">

The state selection control can be setup using FCBKComplete setup scripts as follows:

$("#stateSelection").fcbkcomplete({
json_url: '<%=Url.Action("GetStates", "Profile") %>',
cache: false,
json_cache: false,
filter_case: false,
filter_hide: false,
firstselected: false,
filter_selected: true,
maxitems: 3,
complete_text: "Enter States..."
});

The auto-complete can be simply done by creating a Controller action that returns the JSON result as shown:

public JsonResult GetStates(string tag)
{
    JsonResult result = new JsonResult();

    List tags = TypeDataServiceInstance.SearchStates(tag);
    if (tags != null)
    {
          var data = from r in tags
                         select new
                         {
                            caption = r.Name.Trim(),
                            value = r.StateProvinceId.ToString()
                         };
           result = Json(data);
           result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

   return result;
}

When the form postback occurs, the user can then save the data over to the database. However, this is a little strange because the FCBKControl requires you to name the control as controlname[]. This is an issue because we cannot possibly use this as a Controller parameter since we can’t name arguments ending with [] as parameter names. For this, there is a small hack that you have to apply. The Request.Form object comes in handy for situations like these.

if (Request.Form["stateSelection[]"] != null)
{
        stateIds = Request.Form["stateSelection[]"].ToString();
}

This retrieves the state id’s as a CSV list.

Alternatively, you could also use a Action Filter. To read more about how you could use an action filter, read Haack’s post here.

In the EDIT mode the user can view previously selected states, optionally add more, and also remove existing selections from the list.
FCBKComplete provides us with a nifty little trigger called “AddItem” that allows you to manually add items to the textbox. This aids in displaying pre-selected values.

In order to pre-populate the FCBKComplete, the following method can be used:

function loadStateData() {
$.getJSON('<%= Url.Action("GetSelectedStates", "Profile") %>',
{ currentTime : '<%= DateTime.Now %>' }, function(data) {
for (var i = 0; i < data.length; i++) {
$("#stateSelection").trigger("addItem", data[i]);
}
});
}

Of course, there is the whole issue of JSON Caching on IE which needs to be addressed. This was simply handled by passing in the current date time as a parameter to the JSON action call which makes the browser make a brand new request. To read more about the Controller action implementation, see this previous post of mine.

The rest is simple. On the form postback, obtain the CSV field, parse it out and then call your Service and repository classes to save the data to the database.

Hopefully this helps some folks out there. It took me a while to gather all the documentation from different sites, blogs and comments until I finally got this right.

Rock on Developers! Rock on!