Skip to main content

AutoComplete TextBox with ASP.NET MVC and jQuery

jQuery UI has an AutoComplete widget. The autocomplete widget is quite nice and straight forward to use. In this post, how to integrate the AutoComplete widget with an ASP.NET MVC application.
The first step is to add the jQuery scripts and styles. With ASP.NET MVC 4, the following code does the work:
@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")    
@Scripts.Render("~/bundles/jqueryui")
Using the AutoComplete widget is also simple. You will have to add a textbox and attach the AutoComplete widget to the textbox. The only parameter that is required for the widget to function is source. For this example, we will get the data for the AutoComplete functionality from a MVC action method.
$(document).ready(function () {
    $('#tags').autocomplete(
        {
            source: '@Url.Action("TagSearch", "Home")'
    });
})
In the above code, the textbox with id=tags is attached with the AutoComplete widget. The source points to the URL of TagSearch action in the HomeController: /Home/TagSearch. The HTML of the textbox is below:
<input type="text" id="tags" />
When the user types some text in the textbox, the action method - TagSearch is called with a parameter in the request body. The parameter name is term. So, your action method should have the following signature:
public ActionResult TagSearch(string term)
{
    // Get Tags from database
    string[] tags = { "ASP.NET", "WebForms", 
                    "MVC", "jQuery", "ActionResult", 
                    "MangoDB", "Java", "Windows" };
    return this.Json(tags.Where(t => t.StartsWith(term)), 
                    JsonRequestBehavior.AllowGet);
}
With the above code, the AutoComplete functionality is complete. Quite simple, right?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>

Comments

Popular posts from this blog

create a table in SQL

To create a table, you can follow this formula: CREATE TABLE Country( Column1 , Column2 , Column3 ) or: CREATE TABLE Country( Column1 , Column2 , Column3 ); Each column is created as: ColumnName DataType Options Here is an example: CREATE TABLE Customers ( DrvLicNbr nvarchar(32), DateIssued DATE, DateExpired date, FullName nvarchar(50), Address NVARCHAR(120), City NvarChar(40), State NVarChar(50), PostalCode nvarchar(20), HomePhone nvarchar(20), OrganDonor BIT); GO To start from a sample code, open an empty Query window and display the Template Explorer. From the Template Explorer, expand Table. Drag Create Table and drop it in the Query window: -- ========================================= -- Create table template -- ========================================= USE <database, sysname, AdventureWorks> GO IF OBJECT_ID('<schema_name, sysname, dbo>.<table_name, sysname, sample_table>', 'U') IS NOT NULL DROP TABLE <schema_name, sysname, d...

Stored Procedures

Practical Learning: Introducing Stored Procedures Start Microsoft  SQL  Server  Management  Studio  and log in to your  server On the main menu, click File -> New -> Query With Current Connection To create a new database, copy and paste the following code in the Query window:   -- ============================================= -- Database: WattsALoan -- ============================================= USE master GO -- Drop the database if it already exists IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'WattsALoan' ) DROP DATABASE WattsALoan GO CREATE DATABASE WattsALoan GO -- ========================================= -- Table: Employees -- ========================================= USE WattsALoan GO IF OBJECT_ID(N'dbo.Employees', N'U') IS NOT NULL DROP TABLE dbo.Employees GO CREATE TABLE dbo.Employees ( EmployeeID int identity(1,1) NOT NULL, EmployeeNumber nchar(10) NULL, FirstName nvarchar(20) NULL, LastName nvarcha...

Delete a table in SQL

To delete a table using SQL, use the following formula: DROP TABLE TableName The  DROP TABLE  expression is required and it is followed by the name of the undesired table. Here is an example: DROP TABLE Students; GO