Skip to content

jQuery Search box and Asp.net MVC

April 9, 2009

This is a simple run through on how to create a fancy search box, that has suggestions underneath the input box, and that also can do autocomplete. For this example I used the Chinook database from codeplex and the Artists table and the autocomplete jquery plug-in that you can find at pengoworks.com.

There are plenty of jQuery plug-ins that do the same thing, I picked this one as it’s very easy to use. As the docs show, the only thing you need to do is hook your input text box up to autocomplete and provide the url where it gets it’s data from. The view looks like this.

<asp:Content ID="headerContent" ContentPlaceHolderID ="headerPlaceHolder" runat ="server">
  <script type="text/javascript" src="../../Scripts/jquery.autocomplete.js"></script>
  <link href="../../Content/jquery.autocomplete.css" rel="stylesheet" type="text/css" />

  <script type="text/javascript">

    $(document).ready(function() {
      $("#searchTerm").autocomplete("/Artists/getAjaxResult/");
    });

  </script>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Look for an artist</h2>

    <form action="/Artists/Search" method="post" id="searchForm">
      <input type="text" name="searchTerm" id="searchTerm" value="" size="10" maxlength ="30" />
      <input type ="submit" value="Search" />
    </form>
    <br />

</asp:Content>

As you can see I usually have a container in the header of the master page where javascript and custom css files go. Note that you should use the Url.Content method so you get the proper urls when you deploy this on a ‘real server’.

Now for the backend, we need an action that returns a string of results to the autocomplete call.

        public ActionResult getAjaxResult(string q)
        {

            string searchResult = string.Empty;

            var artists = (from a in _db.Artists
                           where a.Name.Contains(q)
                           orderby a.Name
                           select a).Take(10);

            foreach (Artist a in artists) {
                searchResult += string.Format("{0}|\r\n", a.Name);
            }

            return Content(searchResult);
        }

By using linq to sql I get the top 10 results from the database from the Artists table and return that as a string to the autocomplete call. The user’s input string is a string called q that is put into the action as a url parameter like this: artists/getAjaxResult/?q=symphony. In order to make that work, you need to add a route to the routes table.


            routes.MapRoute(
                "ArtistSearch",
                "Artists/Search/{searchTerm}",
                new { controller = "Artists", action = "Search",
                            searchTerm = "" }
            );
            routes.MapRoute(
                "ArtistAjaxSearch",
                "Artists/getAjaxResult/",
                new { controller = "Artists", action = "getAjaxResult" }
            );

The first route is used once the user has pressed the submit button, the ArtistAjaxSearch is used for the autocomplete script.

So what happens when the user presses the submit button, whether or not he picked an item from the autocomplete results ?

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Search(string searchTerm)
        {
            if (searchTerm == string.Empty)
            {
                return View();
            }
            else
            {
                // if the search contains only one result return details
                // otherwise a list
                var artists = from a in _db.Artists
                              where a.Name.Contains(searchTerm)
                              orderby a.Name
                              select a;

                if (artists.Count() == 0) {
                    return View("notfound");
                }

                if (artists.Count() > 1)
                {
                    return View("List", artists);
                }
                else
                {
                    return RedirectToAction("Details",
                        new { id = artists.First().ArtistId });
                }
            }
        }

As you can see, when a single result is found the details view is shown to the user, by using a redirect to the details method. If there is more than one result, the list of artists is shown. When nothing is found, a simple message is shown. You can of course move the search term to that view as well, to show the user what input he did etc., but that is straightforward stuff.

Another way to do this, would be to insert the artist table as an array and let the autocomplete script use those values for it’s magic, all on the client side. This would be doable as long as that table wouldn’t get too long. If there are 1000s of records, this wouldn’t be a very good solution ;).

Hope this helps someone out there :), feel free to add any comments or questions !

kick it on DotNetKicks.com

About these ads
28 Comments
  1. April 13, 2009 6:27 am

    Great Post! One thing I would be cautious on is in the Search Action Method assuming that if one artist is returned from the query that is the correct artist. I would think from a user experience factor that doing a search that only returns one result would still show the search listing with just the one result posted. The user can then decide to click through to the details page or search again…

    • April 13, 2009 3:37 pm

      Thanks :).

      Yes I think that’s a matter of personal preference. When I search and I get a list of just one item, I always wonder why not just show me the details of the one thing ;).

  2. Graham permalink
    April 14, 2009 6:24 am

    Chances are you will want string ToLower() the a.Name call if you want case invariant matching.
    Thanks for the article!

  3. April 30, 2009 1:59 am

    thanks

  4. Mike Scott permalink
    May 21, 2009 7:51 pm

    Cool post! One thing you might want to do is use a StringBuilder instead of concatenating your strings in getAjaxResult(…).
    ;)

  5. May 26, 2009 2:14 pm

    good example, thx :)

  6. GGG permalink
    June 12, 2009 12:28 pm

    It dioesnt work for me

  7. July 27, 2009 1:39 pm

    Tnx for this fancy searchbox only the autocomplete doesn’t work :(

    • July 27, 2009 2:22 pm

      It’s one of the many options you can use with the autocomplete script, where you want autocomplete or not. So maybe you just need to turn it on !

  8. December 16, 2009 7:53 am

    I’m interested in using this same functionality on a site I’m developing. However, the site is coded in VB. Can you provide the VB equivalent of the C# presented in your post?

    • December 16, 2009 9:53 am

      No I am afraid not. I am not a MS employee of some sort, you’ll have to figure that out on your own.

  9. Muhammad Arshad permalink
    January 6, 2010 12:02 pm

    It seems nice solution please can you send me source code of this sapmle project

  10. April 19, 2010 12:33 pm

    Good Example ,thanks ………..

  11. April 22, 2010 12:34 pm

    sohbet, chat, mirc, muhabbet, adatr, sanal sohbet
    Crap, didn’t realise that would happen :-)
    If I remove the li tags then the link works.

  12. pankaj permalink
    May 15, 2010 5:47 pm

    thats good

  13. Bhoomi permalink
    September 9, 2010 8:08 am

    Could you please provide an example for using autocomplete in editing the jqgrid.
    M stuck there. Searched everything but no clues. My autocomplete just does not work.

    Thanks,
    Bhoomi.

  14. April 8, 2011 2:25 pm

    x0yZET http://dhY3n0fjvTtj48mG9sFnCv.com

  15. July 28, 2011 3:05 pm

    NsvaQN http://fnYwlOpd2n9t4Vx6A3lbk.com

  16. vince permalink
    August 22, 2011 11:40 pm

    Thank you , it was very useful for a beginner like me….it worked like a treat…

  17. September 26, 2011 12:27 am

    Have you got any ? Kds Sex 8DD

  18. October 16, 2011 7:51 pm

    dfgdsgdf

  19. October 26, 2011 10:48 pm

    I’d like to cancel a cheque Preteen Nudes
    97281

Trackbacks

  1. 9eFish
  2. ASP.NET MVC Links :: eric.ness.net
  3. Interesting Finds: 2009-04-20 - Bolik
  4. 10+ JavaScript & jQuery MVC Tutorials | jQuery4u
  5. Share 16 of the MVC tutorial javascript & jQuery - Open News

Comments are closed.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: