jQuery UI Autocomplete Widget with ASP.NET VB

You might also be interested in the Using jQuery Autocomplete to Populate Another Autocomplete post.

As a follow up to the jQuery UI Autocomplete Widget with ColdFusion and the jQuery UI Autocomplete Widget with PHP posts, I did one with ASP.NET (VB.NET) as the backend. I swear this is the last one I’m doing. I’m running out of languages that I work in.

The jQuery UI folks have released an autocomplete widget that is pretty slick. This example uses the JavaScriptSerializer() function in .NET 3.5. I heard a rumor .NET 4 might make this json encoding with data easier. We’ll see.
autocomplete
This example will use US states and territories to populate the autocomplete. It will also demonstrate how to fill other fields with data returned from the database. This data can be used to fill a visible text box or a hidden form field. It also demonstrates the basic autocomplete functionality which may be fine for some applications.

Of course, you will need the jQuery core file, the jQuery UI core file, and the jQuery UI style sheet of choice. The style sheet comes from the themes available in the jQuery UI website and can be downloaded with the core file or you can link to the latest versions of both the core files and the css:

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" /> 
 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>

The HTML is straight forward and stripped down for the example:

<form action="Default.aspx"  method="post">
<fieldset>
<legend>jQuery UI Autocomplete Example - ASP.NET VB Backend</legend>
<p>Start typing the name of a state or territory of the United States</p>
<p class="ui-widget"><label for="state">State (abbreviation in separate field): </label>
	<input type="text" id="state"  name="state" /> <input readonly="readonly" type="text" id="abbrev" name="abbrev" maxlength="2" size="2"/></p>
    <input type="hidden" id="state_id" name="state_id" />
<p class="ui-widget"><label for="state_abbrev">State (replaced with abbreviation): </label>
<input type="text" id="state_abbrev" name="state_abbrev" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</fieldset>
</form>

As a bonus, we dump out the form values to see what we have right underneath the form itself:

Sub Page_Load(Source As Object, E As EventArgs)  
 	Dim formfields As String = "<p>" 
	
     For Each sItem In Request.Form
	 	formfields = formfields + "<strong>" + sItem + "</strong> = " +  Request.Form(sItem) + "<br />"
  	Next  
	formoutput.Text = formfields + "</p>"
 End Sub  

And the jQuery on the page is equally brief:

$(function() {
        
            $('#abbrev').val("");
            
            $("#state").autocomplete({
                source: "states.aspx",
                minLength: 2,
                select: function(event, ui) {
                    $('#state_id').val(ui.item.id);
                    $('#abbrev').val(ui.item.abbrev);
                }
            });
            
            $("#state_abbrev").autocomplete({
                source: "states_abbrev.aspx",
                minLength: 2
            });
        });

Notice that there are two autocomplete functions on the page, one for each example in the demo. Each function calls a different aspx file which return slightly different result sets.

Also, the minLength for autocomplete to return results is set to 2 to prevent too many rows from being returned.

The jquery autocomplete will append the text typed into the autocomplete field as the URL parameter ‘term.’ This URL parameter is used to query the database.

From the jquery documentation:

The request parameter “term” gets added to that URL.

Both .NET pages return the data after a few steps:

  1. It creates a new javascript serializer
  2. It creates an object to hold the data from each returned row in the query
  3. It queries the database and fills a dataset (keep reading if you like readers better)
  4. Loops an array of the query results adding each row to an object
  5. Adds the object to an ArrayList
  6. Outputs the ArrayList as JSON data

The states.aspx file returns the id field, the state field as ‘value’, and the abbrev field. These values are placed in the appropriate text boxes by the autocomplete jQuery function.

<%@ Page Language="VB" Debug="false" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>


<script runat="server">
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()
        Response.Write(JSONData(Request.QueryString("Term")))
    End Sub
    
    Public Class State
        Public id As Integer
        Public value As String
        Public abbrev As String
    End Class

    Private Function JSONData(ByVal term As String) As String
        
        Dim stateArray As New ArrayList
        Dim index As Integer = 0
        
        Dim objConn As New SqlConnection("YOUR-CONNECTION-STRING-HERE")
        Dim myds As New DataSet("States")
        
        objConn.Open()
       
        Dim adapter As New SqlDataAdapter("SELECT id, state, abbrev FROM states WHERE state like '%' + @ac_term + '%'", objConn)
        adapter.SelectCommand.Parameters.Add("@ac_term", SqlDbType.VarChar)
        adapter.SelectCommand.Parameters("@ac_term").Value = term
        adapter.Fill(myds, "States")

        For Each dr As DataRow In myds.Tables(0).Rows
            Dim st As New State()
            st.id = dr("id").ToString()
            st.value = dr("state").ToString()
            st.abbrev = dr("abbrev").ToString()
            stateArray.Add(st)
        Next
        
        objConn.Close()
        
        Return serializer.Serialize(stateArray)
    End Function
    
    </script>

The states_abbrev.aspx shows the basic functionality of the autocomplete function by just assigning results of the query to the ‘label’ and ‘value’ fields. Explanation on the ‘label’ and ‘value’ fields from the jQuery UI site:

Very important information below. Please read and understand before expecting the autocomplete to work properly.

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.”

<%@ Page Language="VB" Debug="false" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()
        Response.Write(JSONData(Request.QueryString("Term")))
    End Sub
    
    Public Class State
        Public label As String
        Public value As String
    End Class

    Private Function JSONData(ByVal term As String) As String
        
        Dim stateArray As New ArrayList
        Dim index As Integer = 0
        
        Dim objConn As New SqlConnection("YOUR-CONNECTION-STRING-HERE")
        Dim myds As New DataSet("States")
        
        objConn.Open()
        
        Dim adapter As New SqlDataAdapter("SELECT id, state, abbrev FROM states WHERE state like '%' + @ac_term + '%'", objConn)
        adapter.SelectCommand.Parameters.Add("@ac_term", SqlDbType.VarChar)
        adapter.SelectCommand.Parameters("@ac_term").Value = term
        adapter.Fill(myds, "States")

        For Each dr As DataRow In myds.Tables(0).Rows
            Dim st As New State()
            st.label = dr("state").ToString()
            st.value = dr("abbrev").ToString()
            stateArray.Add(st)
        Next

		objConn.Close()
        
        Return serializer.Serialize(stateArray)
    End Function
    
    </script>

Usual recommended jQuery and .NET reading:



Posted in .net, jquery, Web development. Tags: , , . Permalink. Both comments and trackbacks are closed.

18 Comments

  1. Tom
    January 27, 2011 at 3:55 pm | Permalink

    I have used this code successfully to make trivial pages, but when I try to implement them in search pages that contain Master pages and ascx pages things don't seem to go as well. Is there some real life, not "Hello World", examples? I would like to rip out the AjaxControlToolkit, which is not able to do some things needed for autocomplete.

    Thanks

    P.S. I am still on 2.0 Framework but that should not matter.

  2. October 7, 2010 at 7:17 am | Permalink

    @Brad

    In the JSON string, make sure you have set a 'value' or 'label' item with data. It may be getting called, just not finding the data it is looking for. The autocomplete needs a 'value' and/or 'label' item with data returned to populate the select list.

  3. Brad
    October 6, 2010 at 9:08 pm | Permalink

    I have my 'InventoryList.aspx' page created and returning a nice JSON list of inventory items for my page.

    The problem is that it does not get called.

    I am doing this at the top of the page

    $(document).ready(function() {

    $("input[name='tbTitle_1']").autocomplete({
    source: "InventoryList.aspx",
    minLength: 2,
    select: function(event, ui) {
    $('tbTitle_1').val(ui.item.Title);
    $('tbSalesPrice_1').val(ui.item.Sale_Price);
    }
    });
    });

    What would cause the autocomplete to NOT call my source page?

  4. Stewart Celani
    September 7, 2010 at 5:26 am | Permalink

    Hi – I think you've got the wrong jQuery string? Its referencing a php file and not aspx. Is anything else different when working with aspx?

  5. Hemal Desai
    August 24, 2010 at 9:58 am | Permalink

    I am getting an error in
    "parseJSON: function(data)"
    in line jQuery.error("Invalid JSON: " + data)

  6. Hemal Desai
    August 11, 2010 at 3:42 pm | Permalink

    Please Send the zip file i will build the database

    Thanks for your reply

    Hemal

  7. August 10, 2010 at 7:22 pm | Permalink

    @Hemal
    I can zip it up but it will not work unless you hook it to a database with US states and abbreviations in a table.

  8. Hemal Desai
    August 10, 2010 at 2:34 pm | Permalink

    Hello

    Could you please send demo with source to my email?
    I tried with the above code but i am getting an error
    may be i missed copy and paste code to wrong aspx.

    Thanks
    Hemal Desai

  9. June 2, 2010 at 8:18 am | Permalink

    @Avishek
    I do not believe there is an error in the code as it is pulled directly from the demo. You need to create the database and put the code in your own pages.

  10. Avishek Kumar
    June 1, 2010 at 10:53 am | Permalink

    Hello,
    I have read and tried but there seems to be some sort of error in the code above as it is not working as expected,
    please would you send me a download ".zip" file of this fully tested/working/running program,it would be helpful.

    Thanks

One Trackback

  1. [...] http://www.jensbits.com/2010/04/14/jquery-ui-autocomplete-widget-with-asp-net/ Categories: Asp.net, Jquery Tags: Asp.net, Autocomplete, Autocomplete with Jquery, autosuggest, hidden field Jquery autocomplete, Jquery, Jquery autocomplete demo with asp.net, Jquery Autocomplete server side, Jquery Autocomplete with aspnet, Jquery cachelength problem, Jquery caching error, Jquery caching problem, Jquery result, Jquery result handler, jquery UI autocomplete, jquery ui autocomplete with asp.net Comments (0) Trackbacks (0) Leave a comment Trackback [...]