April

14

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:

<link type="text/css" href="jquery-ui-1.8rc3.custom.css" rel="stylesheet" /> 

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8rc3.custom.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.php",
                minLength: 2,
                select: function(event, ui) {
                    $('#state_id').val(ui.item.id);
                    $('#abbrev').val(ui.item.abbrev);
                }
            });

            $("#state_abbrev").autocomplete({
                source: "states_abbrev.php",
                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.

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 mySql As String
        Dim objConn As New SqlConnection("YOUR-CONNECTION-STRING-HERE")
        Dim myds As New DataSet("States")
        mySql = "SELECT id, state, abbrev FROM states WHERE state like '%" + term + "%'"

        objConn.Open()

        Dim adapter As New SqlClient.SqlDataAdapter(mySql, objConn)
        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>

If you prefer to use a reader, just substitute the code below for the dataset code above.

        Dim command As New SqlCommand(mySql, objConn)
        Dim reader As SqlDataReader = command.ExecuteReader()

        While reader.Read()
            Dim st As New State()
            st.id = reader("id").ToString()
            st.value = reader("state").ToString()
            st.abbrev = reader("abbrev").ToString()
            stateArray.Add(st)
        End While

        reader.Close()

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:

“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 mySql As String
        Dim objConn As New SqlConnection("YOUR-CONNECTION-STRING-HERE")
        Dim myds As New DataSet("States")
        mySql = "SELECT id, state, abbrev FROM states WHERE state like '%" + term + "%'"

        objConn.Open()

        Dim adapter As New SqlClient.SqlDataAdapter(mySql, objConn)
        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>

Again, if you prefer to use a reader, here you go:

       Dim command As New SqlCommand(mySql, objConn)
        Dim reader As SqlDataReader = command.ExecuteReader()

        While reader.Read()
            Dim st As New State()
            st.label = reader("state").ToString()
            st.state = reader("abbrev").ToString()
            stateArray.Add(st)
        End While

        reader.Close()

Usual recommended jQuery and .NET reading:



Demo

 

Further Reading:

  1. Using jQuery Autocomplete to Populate Another Autocomplete – ASP.NET, ColdFusion, and PHP Examples
  2. jQuery UI Autocomplete Widget with PHP and MySQL
  3. jQuery UI Autocomplete Widget with ColdFusion

7 Comments for jQuery UI Autocomplete Widget with ASP.NET VB

[...] 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 [...]


Avishek Kumar
June 1, 2010

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


jen
June 2, 2010

@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.


Hemal Desai
August 10, 2010

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


jen
August 10, 2010

@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.


Hemal Desai
August 11, 2010

Please Send the zip file i will build the database

Thanks for your reply

Hemal


Hemal Desai
August 24, 2010

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

Leave a comment

Why ask?

 

« | »