Wednesday, March 19, 2014

How to implement an autocomplete within MVC

In this tutorial to implement AutoComplete, we will go over a simple way to implement. Before doing so, make sure you have references to jQuery. As a reference, I am giving my jQuery references below (as in _Layout.cshtml)



 In creating the UI, it is a very simple design. More concentration would go on the script that ties up data with the text box. Just for the tutorial, I am creating a view named AutoCompleteTest.cshtml

  In our first step, will create a text box and assign an id value, to be referenced further.

   

   Now, will concentrate on getting the autocomplete assigned to this text box, by invoking ajax call to a controller method, which in turn would return a type of List<string> with dynamically generated values as data source for our example.

 Below is the script that we will be using to invoke it. Will go one by one on why and how it is used.


 To initiate autocomplete, we would use jQuery to get the id of textbox and invoke its autocomplete method as $("#txtautocomplete").autocomplete();

If we have an array declared, we can still assign that data as a source or we can write a function as above to invoke ajax call (better with MVC approach) and display the data on its successful get.

Here we declare the datatype is json, since our controller will be returning only json data. Parameter to our controller will be sent via the data option.  Everything else, is a regular definition of an ajax call.

Here, I had defined minLength:1, which indicates, as soon as I start typing, I prefer the autocomplete to start working (hitting my controller method to return matching data). Also for open function, I am trying to set the z-index value to be 1000. This is just to be safe and make sure our autocomplete drop down doesn't be hidden when typing values (more possibility that others with greater z-index might overlap).

  Now that we have everything setup in the UI, lets go create a controller method to return data in json format.

I had written this initial code, just to load the view without doing any thing. Now, will write a method to return data based on the parameter passed.

In this method, I am creating a list type of List<string> and load it with data, by looping through and adding it to them.

Once I have the data ready, I would filter it based on the parameter passed, which is searchtext here and return the filtered list as json result set, back to my view.  Now, we have set up everything that is required to implement autocomplete in MVC. When we run and test it, you should see something like this....






Happy coding....

No comments:

Post a Comment