Monday, February 3, 2014

Simple jQuery Autocomplete using Asp Net MVC

In this tutorial I will explain how implement jQuery Autocomplete Search functionality using Asp .Net MVC andTwitter Typeahead.js library.
This is continuation to my previous post A Simple jQuery Autocomplete Search Tutorial
As I explained in my previous post Twitter Typeahead.js is An open source autocomplete JavaScript library by Twitter.It comes with rich set of features. I explained about ‘local’ and ‘prefetch’ attributes in that post.
And If you want to retrieve data from server as-you-type  we have to use ‘remote’ attribute in Twitter Typeahead.js.
Open your visual studio create a simple MVC application which contains
one controller HomeController.cs and one view page Index.aspx
Add HTML Code Index.aspx view page

And now in the same page add following jQuery Code

Everything is same as previous example except for the “remote” attribute.

The code is straight forward we are passing queryString to a method called GetData() which return jSon data based upon input query in HomeController.
Typeahead.js  ’%QUERY’  keyword will give input search keyword which is a queryString to server.
Now we will define GetData() method in HomeController.cs file

I defined one class called TagSys which contains tag,name,description as properties. And I added one method called GetTagList() which setups some hard coded data.
We can get the data from Database also but to simplify the code I am hard coding here. You can add your own Database Logic to retrieve data based upon queryString.
And I declared GetData() method which takes queryString as input and return jSon data based upon queryString. The Logic is straight forward no need to explain.
And the Demo will look like this.
jQuery Auto Complete using Asp Net MVC
jQuery Auto Complete using Asp Net MVC
It same as previous example the difference is previous example uses ‘prefetch’ attribute which stores Json data in localStorage where as this ‘remote’ attribute return the results as-you-type from Server.
Download the source code for jQuery autocomplete using Asp Net MVC.

No comments:

Post a Comment