Archive for category jQuery UI and ASP.NET

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.

jQuery UI Autocomplete Demo

Any questions? Just leave a comment and I will try to help.

VN:F [1.9.17_1161]
Rating: 7.7/10 (14 votes cast)

No Comments

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:

 

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:

jQuery Selectable Plugin with ASP.NET

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.

VN:F [1.9.17_1161]
Rating: 8.2/10 (9 votes cast)

No Comments

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?

jQuery UI DatePicker

jQuery UI DatePicker Themes

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:

 

jQuery UI DatePicker Demo

jQuery UI DatePicker Demo Page

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 …

  1. You can also check how to integrate Autocomplete jQuery UI widget with ASP.NET
  2. And you can read more about configuration options which Datepicker offers.
And here you can download ASP.NET project with code from this post.
VN:F [1.9.17_1161]
Rating: 7.9/10 (17 votes cast)

No Comments

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:

Google Predictive Search

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

Predictive Search

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:

 Predictive Search

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.

VN:F [1.9.17_1161]
Rating: 7.3/10 (15 votes cast)

20 Comments