How to Improve Performance of jQuery Autocomplete
With autocomplete functionality, expectation of end user, is that autocomplete hints will be visible almost instantaneously while typing a word. In systems which have high volume of data quick response times can be huge challenge. In such case, the usual approach is adding caching layer so that all (or at least most common) requests hit cache instead of database. This way jQuery UI autocomplete widget will get responses much faster.
Below is an example of ASP.NET webservice method which is called by jQuery UI Autocomplete widget. (here you can learn how to use jQuery UI Autocomplete with ASP.NET step by step) In this method, all requests are delegated straight to a database:
[WebMethod]
public string[] GetAllPredictions(string keyword)
{
var db = new DatabaseDataContext();
return (from clients in db.Clients where clients.Name.StartsWith(keyword) select clients.Name).ToArray();
}
From end user’s perspective everything works as it’s expected, method returns correct data. But when number of records in database is significant, this approach is simply slow. This is exactly when caching of data can be useful. Below you can see how this method can be re-written to use ASP.NET web application cache.
[WebMethod]
public string[] GetAllPredictions(string keyword)
{
var db = new DatabaseDataContext();
string[] predictions;
if (!CacheHelper.Get(keyword, out predictions))
{
predictions = (from clients in db.Clients where clients.Name.StartsWith(keyword) select clients.Name).ToArray();
Thread.Sleep(4000); // this is here to simulate slow database
CacheHelper.Add(predictions, keyword);
}
return predictions;
}
Interesting things start from line 7 where we are checking if there are data for given keyword in cache. If data are already there, then we simply return them. If not, then everything that is inside if {…} section will be executed. Which means that data for the keyword will be loaded from database. In line 10 we simulate slow database by stopping entire thread on 4 seconds. And finally, in line 11, data from database are added to cache. This way, next time, there will be no need to go to the database.
CacheHelper class is a small, but very useful class, which you can download together with a sample project. But you can also read about it in C# Cache Helper post.
Cache Helper will cache data for 1 day. If this is fine for you then you can be treat Cache Helper as a black box. But if you want to refresh your data more often, then you need to modify this method in CacheHelper class:
public static void Add(T o, string key)
{
// NOTE: Apply expiration parameters as you see fit.
// I typically pull from configuration file.
// In this example, I want an absolute
// timeout so changes will always be reflected
// at that time. Hence, the NoSlidingExpiration.
HttpContext.Current.Cache.Insert(
key,
o,
null,
DateTime.Now.AddMinutes(1440),
System.Web.Caching.Cache.NoSlidingExpiration);
}
In line 13, cache expiration is set to 1440 minutes, which is 1 day. Here you can change it to a different value. As it’s suggested in the comment, settings for cache, can be also loaded from configuration file, but this is a different topic.
In the above solution, cache will be filled only with data which people actually use. The drawback of this solution is that visitor which will request data which are not in cache, will have to wait a bit longer. One way to overcome this problem is pre-cache some of the keywords. Or you can even pre-cache all keywords if you don’t have many combinations. Pre-caching can be done during application start. To do that, the easiest way is to use application_start event. In Global.asax.cs file you have to add this code:
void Application_Start(object sender, EventArgs e)
{
CacheHelper.Add(new [] { "Intel (from cache)", "Intel 2" } , "int");
}
The above code, after starting the application, will add data to the cache. Visitors which will enter “int” will get 2 hints: “Intel (from cache)” and “Intel 2″. Even first response will be fast.

What you can see in Application_Start method is of course a dummy implementation. I want just to give you an idea how pre-caching can be achieved. In real life you will want to do something more clever. Ideally you want to cache everything. But when number of combinations is vast, this may not be practical. So if you can’t cache everything, then you need to have some way to determine which keywords are popular and cache only them.
Ajax File Upload With ASP.NET Using Valums’ Script
Ajax file upload is a very popular extension to all ASP.NET web applications. Thanks to ajax it’s possible to upload files without page reload. On top of that user experience can be improved by features like progress bar, drag and drop or possibility to select multiple files at once. ASP.NET developer to incorporate ajax file upload extension has to cope with two major challenges:
- Find the best, the easiest to integrate and the easiest to tweak JS library
- Integrate the library with actual ASP.NET application
In this tutorial I will show you how to integrate ASP.NET application with ajax file upload script created by Andrew Valums. I don’t know if this is the best script available out there, but for sure it’s really good. It’s easy to integrate with ASP.NET, easy to tweak and style in a custom way. Here is how to do it:
How to integrate Valums’ Ajax File Upload Script with ASP.NET
First step is to download the latest version from Valums’ site.
Here are essential files to use:
- fileuploader.css – default styles, it’s a good starting point to tweak in future
- fileuploader.js – ajax file upload script, this is where the entire logic is
- loading.gif – loading animation, small but cool thing, it’s required by default styles
I have put the above files in the following location in my application:
- [root]\Images\loading.gif
- [root]\Scripts\fileuploader.js
- [root]\Styles\fileuploader.css
On top of that I have added a few additional files:
- [root]\FileUpload.aspx – this is the file where user can upload files. On this page ajax file upload script will be used.
- [root]\FilesUploader.cs – this is http handler which will receive the files, save them and reply to ajax script with appropriate status (success or error). Please remember that http handler to work has to be registered in web.config.
ASP.NET solution with all of the above files you can download from here. I recommend doing so as it will make learning process easier.
Second step is to create ASPX page with upload form.
There are three essential parts:
- Include all relevant scripts and styles:
<script src="Scripts/fileuploader.js" type="text/javascript"></script> <link href="Styles/fileuploader.css" rel="stylesheet" type="text/css" />
- Add HTML in place where upload form should be:
<div id="file-uploader-demo"> <noscript> <p>Please enable JavaScript to use file uploader.</p> <!-- or put a simple form for upload here --> </noscript> </div> - Enable ajax file upload script:
<script type="text/javascript"> function createUploader() { var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-demo'), action: 'FilesUploader.html', debug: true }); } // in your app create uploader as soon as the DOM is ready // don't wait for the window to load window.onload = createUploader; </script>
In the last step, in line 4 script expects to get an ID of div within which form will be automatically added. In next line, it’s specified URL where the form and files will be posted to.
On this stage page for end visitor is ready, it should even render correctly. But it won’t work if you try to upload something. The missing thing is a “thing” on server side which will take uploaded files and save them somewhere (filesystem, database).
Third step is about adding http handler which will receive uploaded files.
Here is a code to do that:
public class FilesUploader : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
if (IsIE9(request))
{
byte[] buffer = new byte[request.ContentLength];
using (BinaryReader br = new BinaryReader(request.Files["qqfile"].InputStream))
br.Read(buffer, 0, buffer.Length);
string filename = Path.GetFileName(request.Files["qqfile"].FileName);
File.WriteAllBytes(request.PhysicalApplicationPath + filename, buffer);
context.Response.Write("{success:true}");
context.Response.End();
}
else
{
byte[] buffer = new byte[request.ContentLength];
using (BinaryReader br = new BinaryReader(request.InputStream))
br.Read(buffer, 0, buffer.Length);
File.WriteAllBytes(request.PhysicalApplicationPath + request["qqfile"], buffer);
context.Response.Write("{success:true}");
context.Response.End();
}
context.Response.Write("{error:\"Upload failed! Unexpected request.\"}");
context.Response.End();
}
private bool IsIE9(HttpRequest request)
{
return request["qqfile"] == null;
}
#endregion
}
IE9 handles uploaded files in a completely different way than other browsers. Therefore major if checking if file has been uploaded in IE9 is required. Depending on that, there are different methods to access data like file name and input stream.
Uploaded files are copied from request to array of bytes in lines 16 to 18 (for IE9) and 28-30 (for other browsers). In line 21 and 32 array of bytes is saved to a file. Name of file comes from query parameter in majority of browsers. By default name of query parameter is qqfile. File in the above case will be saved in root folder of ASP.NET application. Here is screen showing how the request looks like in firebug:

After saving file, in lines 23-24 and 34-35 http handler responds to the ajax file upload script with information that operation was successful. In lines 38 and 39 is an example how to send to the script information about an error.
One more thing – remember please that to make http handler work, it has be registered in web.config:
<httpHandlers> <add verb="POST" path="FilesUploader.html" type="FirstTestWebApp.FilesUploader"/> </httpHandlers>
After step three, you should be able to upload a file, server should respond with appropriate response, files should be saved in application root folder. Only one small thing has to be done – you might have noticed that on this stage, loading.gif is not displayed when file is being uploaded.
In fourth step you have to tweak fileuploader.css file to make sure it finds the loading.gif animation. Look for .qq-upload-spinner class, this is where you have to update path to the file.
In this tutorial I have showed you how to integrate ASP.NET application with Valums’ ajax file upload script. On Valums’ page you will find all the options which scripts offers. I will list a few, the most interesting ones:
- ability to validation based on extension of the files
- validation based on file size
- ability add custom query parameters to each upload
- there is also an option to override messages and to trigger custom functions on events like upload complete, upload in progress, on submit or on cancel.
Once again, you can download full, working, ASP.NET with ajax file upload solution from here to experiment with.
How to Customize jQuery UI Autocomplete to Update Multiple Fields
This post is a response to frequently asked question – how to customize jquery UI Autocomplete widget with a custom action. Typical use case is a functionality where user can find the nearest office or a local shop. Usually system offers a list of cities to choose from. When the list is long, it makes sense to give user an option to type the city in. That combined with autocomplete feature makes the operation of finding the right office efficient and user-friendly. However after selecting the desired city system should display not only selected city but also additional information like full address, map or phone number. This is exactly where customization of jQuery Autocomplete widget comes into an account.
Customization of jQuery UI Autocomplete widget
Autocomplete widget can work with various data sources, but the most flexibility gives Callback option. Hence this the option I will use to customize the widget. But before that, I need to enhance (compering the code from the initial jQuery UI Autocomplete with ASP.NET post) the ASP.NET webservice to return not only list of strings but list of addresses. Single Address can contain arbitrary number of properties. Here is new version:
[System.Web.Script.Services.ScriptService]
public class PredictiveSearch : System.Web.Services.WebService
{
[WebMethod]
public IList<Address> GetAllPredictionsWithAdditionalData(string keywordStartsWith)
{
//TODO: implement real search here!
// dummy implementation
IList<Address> output = new List<Address>();
output.Add(new Address { StreetAddress = "32 Spring Street", City = "New York", PostCode = "NJ 07302" });
output.Add(new Address { StreetAddress = "32 Spring Street", City = "Boston", PostCode = "NJ 07302" });
output.Add(new Address { StreetAddress = "32 Spring Street", City = "Los Angeles", PostCode = "NJ 07302" });
output.Add(new Address { StreetAddress = "32 Spring Street", City = "Washington", PostCode = "NJ 07302" });
return output;
}
}
public class Address
{
public string City { get; set; }
public string PostCode { get; set; }
public string StreetAddress { get; set; }
}
In second step I will modify jQuery code to work with enhanced ASP.NET webservice and use Callback data source (line 2) to process data accordingly. Within Callback function I will call ASP.NET webservice using ajax() function to get data. The most interesting things are in lines 10 to 24 where data from the webservice are transformed into a format expected by autocomplete widget.
Code has a lot of comments so I think everything should be understandable:
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/PredictiveSearch.asmx/GetAllPredictionsWithAdditionalData",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
// here I will store list of all cities which
// will be passed to autocomplete widget
var autocompleteOutput = [];
// looping to get all the cities out of the list of
// addresses returned by the webservice
$.each(data.d, function (index, address) {
autocompleteOutput[index] = address.City;
});
// passing all the available options to autocomplete widget
response(autocompleteOutput);
// store results in global variable, it will be needed
// later to get the rest of details for selected option
autocompleteData = data.d;
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
}
});
Line 24 is important as this is where the data from webservice are stored in global variable autocompleteData and this way I have access to those data later on from other parts of jQuery code. I will use it in next step – autocomplete widget will trigger change event everytime where value in text input has been changed. I will attach my handler to this event and on each change I will display all the additional information about selected city. Please note that in line 10 I use global variable autocompleteData which contains all the data from the webservice:
change: function (event, ui) {
// ui.item can be null when user didn't select
// any option from displayed hints
// it can happen when user, regardless of displayed hints,
// simply typed something into the text input
// the safest option would be to take value directly from text input
var selectedCity = ui.item ? selectedCity = ui.item.value : selectedCity = $(".searchinput").val();
// find matching element
var matchingElementsArray = $.grep(autocompleteData, function (item) { return item.City == selectedCity; });
// here I'm checking if there is at least 1 matching element,
// I expect to find exactly 1
if (matchingElementsArray[0]) {
// city and address are spans, the easiest way to
// set new values is by using html() function
$("#selectedCity").html(matchingElementsArray[0].City);
$("#selectedAddress").html(matchingElementsArray[0].StreetAddress);
// this is a text input, therefore different way
// of setting the value - val() function
$("#selectedPostCode").val(matchingElementsArray[0].PostCode);
}
else {
// in this case there is something in the text input
// but I don't have any details (address) for it on a client side
// so here can be added a separate AJAX call to a webservice
// to ask for missing data
// something like:
//
// /Services/PredictiveSearch.asmx/GetDetailsForCity
//
// and selected city should be passed as a parameter
}
}
And this is basically it, as usually, you can download the full project with working example to experiment with it on your own.
Any questions? Just leave a comment and I will try to help.
jQuery UI Selectable With ASP.NET
While playing with jQuery UI library I have found great way to utilize jQuery UI Selectable plugin with ASP.NET. It can be used as a replacement for long series of checkboxes. For instance, in my scenario, I had to give authors (it’s a CMS system) ability to create a news and additionally give them an option to select countries relevant for the news. Logic behind it is that later we can easily filter news by country.
The most obvious approach is to give authors list of checkboxes or multiselect list. In my opinion both options are not very pleasant to use. Therefore I was looking for some alternative. And here is what I was able to achieve with jQuery Selectable plugin:

Selectable list of countries implemented with jQuery Selectable
Authors have an option to select countries in a few different ways:
The jQuery UI Selectable plugin allows for elements to be selected by dragging a box (sometimes called a lasso) with the mouse over the elements. Also, elements can be selected by click or drag while holding the Ctrl/Meta key, allowing for multiple (non-contiguous) selections.
On top of that it’s very easy to add functional buttons like ‘Select All’ and ‘Deselect All’.
I think that’s it in terms of introduction, now I will show you how to get jQuery UI Selectable plugin integrated with ASP.NET. Also I will show you how to pre-select some elements and how to add select all (and deselect all) functionality.
How to integrate jQuery UI Selectable plugin with ASP.NET
Step 1 – download jQuery UI on your machine. I was using version 1.8.14.
Step 2 – Make sure that your page has all the required JS and CSS files included. jQuery Selectable plugin has a few dependencies. Here is everything you need:
<link href="Styles/ui-lightness/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css" /> <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <script src="Scripts/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="Scripts/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="Scripts/ui/jquery.ui.mouse.js" type="text/javascript"></script> <script src="Scripts/ui/jquery.ui.selectable.js" type="text/javascript"></script>
Step 3 – HTML
Our goal is to get HTML like this:
<h3>This is Selectable plugin demo!</h3>
<div>
<ol id="selectable">
<li class="ui-widget-content">Argentina</li>
<li class="ui-widget-content">Australia</li>
<li class="ui-widget-content">Austria</li>
<li class="ui-widget-content">Belgium</li>
</ol>
</div>
But it’s not a good idea to hardcode countries in HTML, ASP.NET should generate the list. So on server side we will replace the HTML list with ASP.NET Repeater control:
<h3>This is Selectable plugin demo!</h3>
<div>
<asp:Repeater ID="rptCountries" runat="server">
<HeaderTemplate><ol id="selectable"></HeaderTemplate>
<ItemTemplate>
<li class="ui-widget-content">
<%# ((Country)Container.DataItem).Name %>
</li>
</ItemTemplate>
<FooterTemplate></ol></FooterTemplate>
</asp:Repeater>
</div>
You can see that on server side there is a class Country which has all the country related data. So let’s jump to server side where you will find the details.
Step 4 – ASP.NET code
At the moment, server side code looks like this:
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public partial class SelectableDemo : System.Web.UI.Page
{
// list of countries can be much longer
private IList<Country> countries = new List<Country>() {
new Country () { Id = 1, Name = "Argentina" },
new Country () { Id = 2, Name = "Australia" },
new Country () { Id = 3, Name = "Austria" }
};
protected void Page_Load(object sender, EventArgs e)
{
rptCountries.DataSource = countries;
rptCountries.DataBind();
}
}
One thing worth noticing is that Country class has an Id property which is set for all countries from my example but it’s not used anywhere. It will be required in further steps when we will get the point of saving selected countries.
Step 5 – jQuery code
The final step is to enable jQuery Selectable plugin on our list. This is as simple as this:
$(document).ready(function () {
$("#selectable").selectable();
});
To find our countries list I’m using jQuery selector $(“#selectable”) which will find all tags with ID selectable.
After completing this step you should get list of countries generated by ASP.NET and jQuery Selectable plugin enabled for the list. So in fact you should be able to already select countries which you like.
But the job is not really finished yet! How are you going to save selected countries? How are you going to pre-select countries saved earlier? How to implement select all or deselect all functionality? This is exactly where the fun begins…
Step 1 – Let’s start with changes in HTML generated by ASP.NET, we need to add a few elements there:
- button to save selected countries,
- button to select all countries
- button to deselect all countries
- text box where jQuery will list selected countries – this way it will be easy to get it on server side,
- and a literal to display a message after saving the list – it is not really needed, but it will handy to prove that everything works
- HTML list has to change as well – there will be a new attribute countryid which is not displayed anywhere but it’s a way to give jQuery information about ID of selected country
Here are the changes:
<h3>This is Selectable plugin demo!</h3>
<div>
<asp:Repeater ID="rptCountries" runat="server">
<HeaderTemplate><ol id="selectable"></HeaderTemplate>
<ItemTemplate>
<li
countryid="<%# ((Country)Container.DataItem).Id %>"
class="ui-widget-content">
<%# ((Country)Container.DataItem).Name %>
</li>
</ItemTemplate>
<FooterTemplate></ol></FooterTemplate>
</asp:Repeater>
<br />
<button id="selectall">Select All</button>
<button id="deselectall">Deselect All</button> <br />
<asp:Button ID="btnSaveChanges" runat="server" Text="Save Changes" onclick="btnSave_Click" /> <br />
<asp:Literal ID="litMessage" runat="server" />
<asp:TextBox ID="txbSelectedCountries" runat="server" CssClass="selectedCountries" />
</div>
Step 2 – Changes in ASP.NET, code behind file:
- Country class will have an additional property – Selected,
- Page_Load method has to not only set DataSource for the Repeater, it has to also check which countries are selected and put this information to the text box txbSelectedCountries. jQuery will later parse it and select appropriate countries.
- method btnSave_Click has to be added – within this method, after clicking on ‘Save Changes’ button, we will get list of all selected countries (from text box txbSelectedCountries) and display relevant information in the literal component (litMessage). It also has to update internal list of countries and mark selected countries as selected.
Here are the changes:
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
public partial class SelectableDemo : System.Web.UI.Page
{
private IList<Country> countries = new List<Country>() {
new Country () { Id = 1, Name = "Argentina", Selected = true },
new Country () { Id = 2, Name = "Australia", Selected = false },
new Country () { Id = 3, Name = "Austria", Selected = false }
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptCountries.DataSource = countries;
rptCountries.DataBind();
// add selected countries to a textbox
StringBuilder selectedCountries = new StringBuilder();
foreach (var country in countries)
{
if (country.Selected) selectedCountries.Append(country.Id + ",");
}
txbSelectedCountries.Text = selectedCountries.ToString();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
// mark all in-memory countries as Selected = false
foreach (var country in countries)
{
country.Selected = false;
}
// selected countries are in format: 1,2,5,6,
string[] selectedIds = txbSelectedCountries.Text
.Substring(0, txbSelectedCountries.Text.Length-1).Split(',');
StringBuilder output = new StringBuilder();
foreach (string id in selectedIds)
{
var country = (from c in countries where c.Id.ToString().Equals(id) select c)
.First<Country>();
country.Selected = true;
output.Append(country.Name + "<br/>");
}
litMessage.Text = "Saved Countries: <br/>" + output.ToString();
}
}
IDs of selected countries are stored as a single string, IDs are comma separated, for instance: 1,56,42,2,
Please note that after last ID there is an additional comma.
Step 3 – Changes in jQuery code
This part is the most complex, firstly you need to bind custom function to “selectablestop” event. Custom function will figure out which countries are selected and will update the txbSelectedCountries text box with the IDs:
$(document).ready(function () {
$("#selectable").selectable();
$("#selectable").bind("selectablestop", function (event) {
var result = "";
$(".ui-selected", this).each(function () {
result += this.getAttribute("countryid") + ",";
});
$("input.selectedCountries").val(result);
});
//update selected countries based on value in selectedCountries input (textbox)
var ids = $("input.selectedCountries").val().split(',');
for (var i = 0; i < ids.length - 1; i++) {
$("#selectable li[countryid=" + ids[i] + "]").addClass("ui-selected");
}
});
Additionally, in last lines, jQuery has to parse data from selectedCountries input and select those countries which IDs are there. This way countries selected earlier and saved will appear on page load as selected. Those lines will be executed only once, it’s a way to keep data synchronised between ASP.NET on server side and jQuery on client side.
Next thing to do is to add ‘select all’ and ‘deselect all’ functionality. Here is how to get it done:
$(document).ready(function () {
$("button, input:submit").button();
$("button#selectall").click(function (event) {
$("#selectable li").addClass("ui-selected");
$("#selectable").trigger("selectablestop");
event.preventDefault();
});
$("button#deselectall").click(function (event) {
$("#selectable li").removeClass("ui-selected");
$("#selectable").trigger("selectablestop");
event.preventDefault();
});
});
Three things are important here:
- First line is an example of jQuery UI button plugin used. The only reason why it’s here is make buttons look nice. If you want to use it, it’s not a problem, but you need to add reference to the jquery.ui.button.js file
- Next function is responsible for ‘select all’ functionality. You will find there basic usage of jQuery selectors (“#selectable li”) to find all list items and add “ui-selected” class. In the next line we are manually triggering “selectablestop” event to tell jQuery that selection has been made. As a result our function bound to that event will be executed and IDs of selected countries will end up in text box. And finally event.preventDefault() function prevents button from submitting the form.
- And the last function is responsible for ‘deselect all’ functionality. The only difference is that instead of adding “ui-selected” class we are removing this class to make sure that all countries are not selected.
And this is the final effect after saving the countries:

View after saving the countries
Is that all?
Well, almost – this is all in terms of functionality. You still need to play with CSS a bit to get the final effect like the one on attached screen. It’s not difficult, you can download the code and check modifications which I made, there are very few. Also you can download the project just to play with it and see how it all works together.
You can as well check how to integrate other jQuery UI widgets with ASP.NET like:
You may also need to check other events and options which you use with jQuery UI Selectable plugin.
jQuery UI Datepicker With ASP.NET
jQuery UI Datepicker is another great widget, extremely useful on forms, which can be easily integrated with ASP.NET. There are tones of different datepickers available almost everywhere so big question is why this one is better than other ones?
Here are a few reasons:
- jQuery UI is very well tested
- jQuery UI is based on jQuery framework and very well integrated
- there are 20+ themes available, ready to use, which you can take and make the datepicker to look consistent with your site
- even if available themes are no good for you, you can easily customize it
- it’s easy to integrate with ASP.NET
- it’s flexible, you can configure it to serve you in many scenarios

On top of that, it’s my subjective opinion, but I really can recommend this plugin. I think it should cover 95% of typical scenarios which you can encounter on websites.
Okey, so let’s get started …
How to integrate jQuery UI Datepicker with ASP.NET
Step 1 – download jQuery UI on your machine. I was using version 1.8.14.
Step 2 – Make sure that your page has all the required JS and CSS files included. Datapicker has a few dependencies. Here is everything you need:
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <link href="/Styles/ui-lightness/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css" /> <script src="/Scripts/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.datepicker.js" type="text/javascript"></script>
Step 3 – HTML Code
This part is very simplified of course just to illustrate basic concepts.
<div id="DatepickerDiv" class="demo"> Event start date: <asp:TextBox ID="txtEventStartDate" runat="server" CssClass="DatepickerInput" /><br /> <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" /><br /> <asp:Literal ID="litMessage" runat="server" /> </div>
Basically minimalistic version contains textbox where user will enter a date. Datepicker widget will be attached to exactly this textbox. There is also button which will submit the form and literal to display messages from server.
Step 4 – jQuery Code
$(document).ready(function () {
$(".DatepickerInput").datepicker({ dateFormat: 'dd/mm/yy' });
});
As you can see this is not very complex. In fact specifying date format is optional but I don’t like to leave date formats not specified. I have too many bad experiences from working with multilingual sites. Date format is different even between UK and US so this is one thing which I don’t want to leave for jQuery to figure out.
In this example jQuery finds textbox based on CSS class – this part is responsible for it: $(“.DatepickerInput”). Here you can read more about how to use basic jQuery filters. Datepicker is attached by calling function datepicker(). All parameters are optional, even dateFormat which I used here.
After this step you should be able to get this effect after clicking on txtEventStartDate textbox:

Step 5 – ASP.NET Code
On server side the only missing thing is implementation of btnSave_Click() method:
protected void btnSave_Click(object sender, EventArgs e)
{
DateTime date;
if (DateTime.TryParseExact( txtEventStartDate.Text,
"dd/MM/yyyy", // example: 31/01/2011
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
litMessage.Text = "Parsed event start date: " + date.ToShortDateString();
}
else
{
litMessage.Text = "Error: we were unable to parse the start date: " + txtEventStartDate.Text;
}
}
The most important thing to remember is to use the same date format as it was in jQuery script. You can see that there are differences in Java Script and ASP.NET data format notation. This can be confusing and is something that should be well commented! It is also a good practice to use TryParseExact() method over simply ParseExact(). And the rest I think is self-explanatory
Conclusion
jQuery UI Datepicker can be easily integrated with ASP.NET and I think should be considered as a default datepicker option for majority of websites. Example in this post shows that you need only a few lines on jQuery code to get everything working. Can you see any reason to not follow this approach?
Next steps? Two actually …
- You can also check how to integrate Autocomplete jQuery UI widget with ASP.NET
- And you can read more about configuration options which Datepicker offers.
Button Click Event via Ajax With jQuery
In this post you will see how easy you can simulate button click event via ajax and this way call some ASP.NET server side method. There are number of scenarios in which this trick can be useful but for me the most appealing one are asynchronous autosaves. You have seen it in number of places for sure – basically whenever you give user an option to enter long piece of content, it’s a good practice to implement autosave, just in case, to prevent user’s content from disappearing because of browser crash or session timeout.
Okey, so here is an example how to get asynchronous autosaves working.
Step 1 – Get HTML ready
HTML is very straightforward, all you need is a textarea and a button. Of course you don’t need any button to have autosaves working, button will be used to save final version.
<h3>This is AutoSave demo!</h3> <div> <textarea id="ContentTextarea" cols="50" rows="10"><%=HttpContext.Current.Session["UserContent"]%></textarea> <br /> <button id="SaveContentButton">Save</button> <span id="autosaveUpdates"></span> </div>
There are two additional elements:
- span autosaveUpdates – this is where I will show updates to a user, it’s nice to inform that everything went fine and autosave actually works
- server side call to HTTP Session – I’m going to keep autosaved content in HTTP session, this is definitely not a production viable option, but for this example it will work
Step 2 – ASP.NET method which saves data
There are two things which you need to do to make your ASP.NET method available for jQuery and Ajax calls:
- method has to be public and static,
- and you need to add [WebMethod] attribute
Here is an example with very basic code which stores content in HTTP Session:
[WebMethod]
public static void SaveContent(string content, bool autosave)
{
if (autosave) {
HttpContext.Current.Session["UserContent"] = content;
}
else {
// TODO save data to a database
HttpContext.Current.Session["UserContent"] = String.Empty;
}
}
Step 3 – Button Click Event via Ajax
Before going to autosave functionality, I will show you how to call button click even via ajax with jQuery. So firstly, this is the function which will call ASP.NET method (from step 2):
function SaveDataViaAjax(autosaveMode) {
$("#autosaveUpdates").html("Saving ... ");
methodURL = "/AutoSave.aspx/SaveContent";
parameters = "{'content':'" + $("#ContentTextarea").val() + "', 'autosave':'" + autosaveMode + "'}";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: methodURL,
data: parameters,
dataType: "json",
async: true,
success: function (data) {
if (autosaveMode) {
$("#autosaveUpdates").html("Autosave at " + Date().toLocaleString());
}
else {
$("#autosaveUpdates").html("Data have been saved at " + Date().toLocaleString());
}
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
};
This function will be used to save data after manually clicking on the button and also to autosave content. A few words of explanation:
- URL to the ASPX page and method is: ‘/AutoSave.aspx/SaveContent’
- I need to pass two parameters as this is exactly what is expected by SaveContent() method – content and autosave
- $(“ContentTextarea”).val() returns value of textarea.
- $.ajax() method is responsible for all the ajax calls mechanics.
- please note that ajax() function is configured to make a asynchronous call, hence user interface won’t be blocked even in case when server will need a few seconds to respond.
- success function will be invoked when entire ajax call went fine and error in other case.
- I use simple jQuery selectors to find relevant tags.
I hope that the rest is self-explanatory. If not – let me know!
Now, we need to set this function to be called after clicking on the button, this code will do it:
$(document).ready(function () {
$("#SaveContentButton").click(function (event) {
SaveDataViaAjax(false)
event.preventDefault();
});
});
Step 4 – Autosaves with jQuery
And final step where I just need to do 2 things
- Define AutoSave function
- Tell Java Script to call the AutoSave function every 5 seconds
And here is code which will do all of that:
$(document).ready(function () {
window.setInterval(Autosave, 5000)
});
function Autosave() {
SaveDataViaAjax(true);
}
And this is it, it all together should work like a charm
Essential here is usage of setInterval() function which takes as a parameter name of the function which should be invoked and interval of time how often give function should be invoked. If you like ajax updates then I recommend you reading about about modules and ajax updates every X seconds, you will find more details there.
Conclusions
After reading this post you should know how to:
- simulate button click event via ajax and jQuery
- call ASP.NET method via Ajax after clicking on a button – ajax() jQuery function
- call server-side method periodically with setInterval() function
- create methods in ASP.NET pages which can be invoked by jQuery
And here is the final effect:

jQuery UI Autocomplete With ASP.NET
In this post I want to show you how to integrate ASP.NET with jQuery UI Autocomplete widget. For those of you which don’t know what jQuery UI is here is a bit of introduction:
jQuery UI provides a comprehensive set of core interaction plugins, UI widgets and visual effects that use a jQuery-style, event-driven architecture and a focus on web standards, accessiblity, flexible styling, and user-friendly design.
From practitioner point of view – jQuery UI provides a few very nice and very useful widgets which you can really easily integrate with your application. Great example is Autocomplete widget which I will use in this post. I have found this widget very useful while implementing search functionality for my project. Of course to implement “just” search functionality where user can enter a keyword and click “search” button you don’t need much. And for sure you don’t need any fancy jQuery widgets. In my case additional requirement was to implement predictive search functionalty. That was a massive change for ASP.NET developer because out of the sudden I had to invoke search after each letter entered by a user and present it in a nice way.
Here is a great example how Google did the predictive search:

And here is another example, something like this I will show how to build in this post:

There is no component like that in Visual Studio! So the solution was to use jQuery UI Autocomplete widget.
How to integrate jQuery UI Autocomplete widget with ASP.NET
Step 1 – go to jqueryui.com and download jQuery UI. I was using version 1.8.14
Step 2 – include following JS scripts in your master page
<link href="/Styles/ui-lightness/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css" /> <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery-ui-1.8.14.js" type="text/javascript"></scrpt> <script src="/Scripts/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.position.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.autocomplete.js" type="text/javascript"></script>
On the list above are all jQuery, jQuery UI Autocomplete widget and dependencies. Please note that there is also CSS style on the list – this is required to make Autocomplete widget looks nice
Step 3 – Create a Web Service which will return predictive search results
[System.Web.Script.Services.ScriptService]
public class PredictiveSearch : System.Web.Services.WebService
{
[WebMethod]
public IList<string> GetAllPredictions(string keywordStartsWith)
{
//TODO: implement real search here!
// dummy implementation
IList<string> output = new List<string>();
output.Add(keywordStartsWith + "1");
output.Add(keywordStartsWith + "2");
output.Add(keywordStartsWith + "3");
output.Add(keywordStartsWith + "4");
return output;
}
}
This is an example of web service which returns dummy data. Your job is to take is further and integrate with your system. Good thing is that from this point it’s all .Net so something you should be comfortable with.
Step 4 – HTML Code
<div class="ui-widget">
<asp:Label ID="lblSearch" Text="Search" AssociatedControlID="txbSearchKeyword" runat="server"></asp:Label>
<asp:TextBox ID="txbSearchKeyword" runat="server" CssClass="searchinput"></asp:TextBox>
<asp:Button Text="Go!" runat="server" onclick="Search_Click" />
</div>
<asp:Literal ID="litStatus" runat="server"></asp:Literal>
As you can see HTML code is fairly straightforward. Only standard ASP.NET controls are here. Textbox txbSearchKeyword is the place where users will be entering keywords. So this is also the place where we need to add jQuery Autocomplete functionality. And that will happen in next step …
Step 5 – jQuery code
Firstly, let me show you the simplest possible implementation. It’s very simple so also a bit limited ![]()
Limitation in this case is that search results are static (there are no ajax calls to server for search results). This can work well in scenario where set of all possible options is very limited – for instance you can use it to tag content. Assumption is that set of tags is fairly constant and in total there are below 100 tags in the system.
$(document).ready(function () {
$(".searchinput").autocomplete({
source: ["test", "asp.net", "jQuery"],
minLength: 2
});
});
And here is an example which actually uses Web Service from step 3.
$(document).ready(function () {
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/PredictiveSearch.asmx/GetAllPredictions",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data){
response(data.d);
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
},
minLength: 2
});
});
In both examples searching for predictions will start not straight away after entering 1 letter! It will start after entering 2 letters, parameter minLength is responsible for that. You can see that behind the scene autocomplete functions calls our PredictiveSearch.asmx Web Service, in particular method GetAllPredictions(). In the next line we are passing entered letters as a parameter data.
It’s recommended to have your JS function in a separate file so that HTML code is separated from JS code.
Step 6 – Get Keyword on server side
On this stage, everything should be working now on client side. You should be able to see something this:

The only missing thing is implementation of onClick function called by “Go!” button. Implementation is again dummy, just to show you how to access all the relevant data:
protected void Search_Click(object sender, EventArgs e)
{
litStatus.Text = "Search conducted for keyword: " + txbSearchKeyword.Text;
}
And as far as I’m concerned this all what you need to integrate jQuery UI Autocomplete with ASP.NET. However here you will find more advanced tutorial showing how to customize jQuery UI Autocomplete widget.
Questions? If yes then leave a comment!
You can download the full ASP.NET project here with the jQuery UI Autocomplete integrated - it should help you with experimenting.
Easy Client Side Repeater with jTemplates Part 3
This is the third post in “Easy Client Side Repeater with jTemplates” series. Just to recap quickly – last two posts were about:
- in the first part you can find information about jTemplates plugin and an example how to build client side repeater with jQuery
- second part is showing how to bind data from ASP.NET WebService with the jTemplates client side repeater
ASP.NET developers when asked about the repeater they naturally see something like this:
<asp:Repeater ID="rptSomeRepeater" runat="server"> <HeaderTemplate></HeaderTemplate> <ItemTemplate></ItemTemplate> <AlternatingItemTemplate></AlternatingItemTemplate> <FooterTemplate></FooterTemplate> </asp:Repeater>
In the previous posts I have shown how you can represent all Repeater’s templates in jTemplates. You will find there details regarding all the templates except of the one (two actually) which are needed to achieve effect like this:
Chalange here is to set different CSS class for odd and even rows. This kind of effect is easy to implement with standard server side ASP.NET Repeater by using ItemTemplate and AlternatingItemTemplate. So how it can be reproduced with jTemplates and client side repeater?
ItemTemplate and AlternatingItemTemplate with jTemplates
Here is a small modification to the code from previous parts which is doing the trick:
{#foreach $T.d as record}
<tr class="{#cycle values=['odd','even']}">
<td><a href="{$T.record.WebSite}">{$T.record.Name}</a></td>
<td><a href="mailto:{$T.record.Organizer.Email}">{$T.record.Organizer.Name}</a></td>
<td>{$T.record.Venue.Name}</td>
</tr>
{#/for}
Essential part of the above example, and the only change, is this line: class=”{#cycle values=['odd','even']}”. This part makes sense because it’s within {#foreach} … {#/for} block. It works in a way that for the first item on the list jTemplates will take first item from {#cycle} values – in our case – ‘odd’. For the second item – jTemplates will take second element from the list – ‘even’. And for third it will start from the begining.
Final HTML code will look like this:
Questions? Leave a comment!
Easy Client Side Repeater with jTemplates Part 2
In the first part I have showed you how to use jTemplates plugin to build client side repeater. In this part I will show you how to make that work with data from ASP.NET WebService. That can be done in 3 steps:
Step 1 – Call WebService to Get Data
GetForthcomingEvents = function (successFunction) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/EventsService.asmx/GetTheForthcomingEvents",
dataType: "json",
success: successFunction,
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
}
This is standard example of $.ajax() function usage. URL of the WebService is /Services/EventsService.asmx and function’s name is GetForthcomingEvents().
GetForthcomingEvents() function expects another function as a parameter. That function will be invoked, assuming that call to WebService went fine (success: successFunction). In the next step you will see an exemplary implementation. It won’t be a surprise to you – it is the same function which was already presented in the first part.
Step 2 – Bind Data From WebService to jTemplates template
BindDataToEventsTemplate = function (result) {
// check if jTemplates is loaded
if (!jQuery.fn.processTemplate) {
alert("jTemplates is not loaded");
return;
}
// attach and process the template
$("#Events").setTemplateElement("EventsTemplate");
$("#Events").processTemplate(result);
}
Data returned from the WebService will be passed here. Next, data will be used to “process template” and this way data will be passed to client side repeater.
Step 3 – Get to all working on document ready
$(document).ready(function () {
$("#Events").html("Loading events ....");
GetForthcomingEvents(function (result) {
if (result.d.length > 0) BindDataToEventsTemplate(result);
});
});
This is of course not the simplest possible option. I have added one if statement (if (result.d.length > 0)) to check if there are actually some events returned. I didn’t want to “execute” repeater when there are no events to display. But it’s optional step and can be omitted.
jTemplates in action
Here I want just to remind you essential part of the template which will be used to process the data
{#foreach $T.d as record}
<tr>
<td><a href="{$T.record.WebSite}">{$T.record.Name}</a></td>
<td><a href="mailto:{$T.record.Organizer.Email}">{$T.record.Organizer.Name}</a></td>
<td>{$T.record.Venue.Name}</td>
</tr>
{#/for}
For each record a row like that will be created. For more details please check first part of this post.
Bonus – The WebService
Here you can see my dummy code of the WebService
[System.Web.Script.Services.ScriptService]
public class EventsService : System.Web.Services.WebService
{
[WebMethod]
public Event[] GetTheForthcomingEvents()
{
return new Event[] { GetFirstEvent(), GetSecondEvent() };
}
private Event GetFirstEvent()
{
return new Event
{
StartDate = DateTime.Now,
EndDate = DateTime.Now,
Name = "MTS Conference",
WebSite = "http://microsoft.com",
Organizer = new Contact
{
Email = "john@ms.com",
JobTitle = "CEO",
Name = "John White"
},
Venue = new Venue
{
Address = "Alabama St. 45",
City = "Washington DC",
Name = "Medison Square Garden",
PostCode = "45-233"
}
};
}
private Event GetSecondEvent()
{
return new Event
{
StartDate = DateTime.Now,
EndDate = DateTime.Now,
Name = "Microsoft TechEd North America",
WebSite = http://www.microsoft.com/events/techednorthamerica/",
Organizer = new Contact
{
Email = "john@ms.com",
JobTitle = "CEO",
Name = "Barry Green"
},
Venue = new Venue
{
Address = "Alabama St. 45",
City = "Atlanta",
Name = "Georgia World Congress Center",
PostCode = "30303"
}
};
}
}
public class Event
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Name { get; set; }
public string WebSite { get; set; }
public Contact Organizer { get; set; }
public Venue Venue { get; set; }
}
public class Venue
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostCode { get; set; }
}
public class Contact
{
public string Name {get; set; }
public string JobTitle { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
Now you have all the pieces. Take it, use it, experiment with it and have fun!
I hope that it all makes sense to you … if not then please leave a comment and I will do my best to help you.
Easy Client Side Repeater With jTemplates
In this post I would like to show you how easy you can implement client side repeater. There are a few jQuery plugins which you can use for it. However I recommend using jTemplates. With jTemplates you can easily define a client side templates, here is an example:
<p style="display:none"><textarea id="EventsTemplate" rows="0" cols="0"><!--
<table>
<thead>
<tr>
<th>Event</th>
<th>Contact</th>
<th>Venue</th>
</tr>
</thead>
<tbody>
{#foreach $T.d as record}
<tr>
<td><a href="{$T.record.WebSite}">{$T.record.Name}</a></td>
<td>
<a href="mailto:{$T.record.Organizer.Email}">
{$T.record.Organizer.Name}
</a>
</td>
<td>{$T.record.Venue.Name}</td>
</tr>
{#/for}
</tbody>
</table>
--></textarea></p>
In the above example you can see that template itself is hidden for end users (display:none). Everything within HTML comments will be used. You can easily recognize elements corresponding to well known ASP.NET Repeater elements:
- everything from the very top (<table>) to {#foreach … } represents HeaderTemplate
- everything between {#foreach…} and {/#for} represents ItemTemplate
- and everything under {/#for} is a FooterTemplate
How to Bind Data to Client Side Repeater?
JS code binding data to the jTemplates repeater looks like this:
BindDataToEventsTemplate = function (result) {
// attach and process the template
$("#Events").setTemplateElement("EventsTemplate");
$("#Events").processTemplate(result);
}
Where $(“Events”) selects tag with id “Events” – this is where output will be placed. “EventsTemplate” is the name of our template – check the definition of template (first piece of code). So it’s that easy – firstly you need to set template which you want to use and secondly bind the data and ”process template”. End of story!
Just to make everything perfectly clear – here is an example of my “Events” tag where new events will be added using client side repeater:
<div id="Events"></div>
One additional tip – you can also check, just in case, if jTemplates has been correctly loaded by adding this piece of code:
// check if jTemplates is loaded
if (!jQuery.fn.processTemplate) {
alert("jTemplates is not loaded");
return;
}
In my case I have loaded data to the repeater from ASP.NET WebService. In the next post I will show you how to get it all working together – jTemplates with ASP.NET WebServices.


