Monday, October 27, 2008

Autocomplete using jQuery, MVC, and JSon

jQuery Autocomplete is a great jQuery plugin for developing efficient autocomplete input fields. I used this plugin in an MVC preview 5 application to build an autocomplete input field that fetches the data from a database and passes the result to the front end in JSon format. Following these steps, you should be able write your own autocomplete input field in MVC.

1) Required Downloads: Download the following plugins if you don't already have them in your project.
2) Include the JavaScripts and CSS: Here are the files you should include on your page.


    <script type="text/javascript" language="javascript" src="<%= Url.Content("~/Content/js/jquery.autocomplete.min.js") %>"></script>

    <script type="text/javascript" language="javascript" src="<%= Url.Content("~/Content/js/jquery.validate.min.js") %>"></script>

    <link  href="<%=Url.Content("~/Content/css/jquery.autocomplete.css")%>" type="text/css" rel="Stylesheet" />



3) Set up a method in your MVC controller: I have used LINQ to search against the database. SearchByPerson is a helper method that fetches the results from the database and returns the result as an IEnumerable<Person>. I finally returned the result as Json data type which will be consumed by the front end in step 4.

public class ImageController : Controller
    {
        public ActionResult SearchPerson(string query, int limit)
        {
            if (string.IsNullOrEmpty(query)) return Json(new { PersonId = "-1", 
                                                               FirstName = string.Empty, 
                                                               MiddleName = string.Empty, 
                                                               LastName = string.Empty });
            CMSDataContext cms = new CMSDataContext();
            var result = cms.SearchByPerson(null, null, query);
            var data = from r in result select new { PersonId = r.PersonId.ToString(), 
                                                     r.FirstName, 
                                                     MiddleName = string.IsNullOrEmpty(r.MiddleName) ? string.Empty : r.MiddleName, 
                                                     r.LastName };
            return Json(data);
        }

...


4) Place an HTML input control on the page: The input html will be targeted by the autocomplete jQuery plugin and I'm using a hidden span to store the selected value of the autocomplete input control which is PersonId in this case.

<input id="searchName" size="30" />

<span id="personSearchresult" style="display:none"></span>

5) Bind your input to Autocomplete plugin: In this step I'm binding the input control to the autocomplete plugin. The first parameter is the SearchPerson action in image controller that searches the database. Using parse, you can manipulate how data gets displayed in the dropdownlist and how the selected value gets displayed in the input control as well. The result event is executed when the user selects a value from the dropdown and in my example I'm storing the PersonId returned as Json in Step 3 in a hidden span.

   <script language="javascript" type="text/javascript">
        $(document).ready(function(){
 
            $('#searchName').autocomplete('<%=Url.Action("SearchPerson", "Image") %>', { 
                dataType:"json",
                formatItem: function(data,i,max,value,term){
                      return value;
                },
                parse: function(data){
                    var array = new Array();
for(var i=0;i<data.length;i++) {
                        var tempValue = data[i].MiddleName != "" ? data[i].FirstName + " " + data[i].MiddleName + " " + data[i].LastName : data[i].FirstName + " " + data[i].LastName;
                        var tempResult = data[i].MiddleName != "" ? data[i].FirstName + " " + data[i].MiddleName + " " + data[i].LastName : data[i].FirstName + " " + data[i].LastName;
                        array[array.length] = { data:data[i], value: tempValue, result: tempResult};
                    }
                    return array;
                }
            });
 
            $("#searchName").result(function(event, data, formatted) {
                $("#personSearchresult").html( !data ? "-1" : "" + data.PersonId);
            });

...

Following these simple steps, you should be able to implement an autocomplete control in your ASP.NET MVC application. Hopefully this post gives you a jump start on Autocomplete jQuery plugin in your MVC application.

Hope this helps,
Faraz

4 comments:

Silverlight Travel said...

jQuery MVC Framework is a great combination! But I can not have all ;-) It is enought work to lern Silverlight.

Regards
from Switzerland
Peter Loebel
http://www.silverlight-travel.com/blog/

Mahdi said...

Thank you for your useful post :-)

John S. said...

The result callback never fires for me if a matching result isn't fired. I want to set the associated hidden value to 0 or -1 if the text entered doesn't match.

Noah Heldman said...

Nice job on the MVC side of things! If you have a chance, please check out my jQuery autocomplete/combobox/suggest implementation, FlexBox, at http://www.fairwaytech.com/flexbox, and let me know what you think.

Thanks!
Noah Heldman

Followers

About Me